英文:
decoding XML in golang
问题
我正在尝试解码以下 XML。由于某些原因,我无法解码 Id
。
package main
import (
"encoding/xml"
"fmt"
)
var data = `
<g xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ad="http://www.myschema.com/schema/ad/v1">
<a xlink:href="http://example.com" data-bind="121">lala</a>
<ad:ad id="1060469006">
</g>
`
type Anchor struct {
DataBind int `xml:"data-bind,attr"`
XlinkHref string `xml:"http://www.w3.org/1999/xlink href,attr"`
Id int `xml:"http://www.myschema.com/schema/ad/v1 id,attr"`
}
type Group struct {
A Anchor `xml:"a"`
}
func main() {
group := Group{}
_ = xml.Unmarshal([]byte(data), &group)
fmt.Printf("%#v\n", group.A)
}
英文:
I'm trying to decode the following xml. For some reasons I can't decode the Id
package main
import (
"encoding/xml"
"fmt"
)
var data = `
<g xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ad="http://www.myschema.com/schema/ad/v1">
<a xlink:href="http://example.com" data-bind="121">lala</a>
<ad:ad id="1060469006">
</g>
`
type Anchor struct {
DataBind int `xml:"data-bind,attr"`
XlinkHref string `xml:"http://www.w3.org/1999/xlink href,attr"`
Id int `xml:"http://www.myschema.com/schema/ad/v1 id,attr"`
}
type Group struct {
A Anchor `xml:"a"`
}
func main() {
group := Group{}
_ = xml.Unmarshal([]byte(data), &group)
fmt.Printf("%#v\n", group.A)
}
答案1
得分: 4
你正在解码的结构体正在寻找XML中<a>
元素上的ad:id
属性。这不起作用的原因有两个:
id
属性位于不同的元素上。id
属性不在http://www.myschema.com/schema/ad/v1
命名空间中。没有命名空间前缀的属性不会继承其元素的命名空间,而是属于空白命名空间。
要解决这个问题,首先你需要在Group
中添加另一个字段,标签为xml:"http://www.myschema.com/schema/ad/v1 ad"
,并且该字段的结构体定义需要有自己的字段,标签为xml:"id,attr"
。
英文:
The structs you are decoding into are looking for a ad:id
attribute on the <a>
element in the XML. There are two reasons this isn't working:
- the
id
attribute is on a different element. - the
id
attribute is not in thehttp://www.myschema.com/schema/ad/v1
namespace. Attributes without a namespace prefix do not inherit the namespace of their element: instead they are part of the blank namespace.
So to fix this, first you need another field in Group
with the tag xml:"http://www.myschema.com/schema/ad/v1 ad"
, and the struct definition for that field needs its own field with the tag xml:"id,attr"
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论