[英]decoding XML in golang
I'm trying to decode the following xml. 我正在尝试解码以下xml。 For some reasons I can't decode the Id
由于某些原因,我无法解码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)
}
The structs you are decoding into are looking for a ad:id
attribute on the <a>
element in the XML. 您要解码的结构正在XML的<a>
元素上寻找ad:id
属性。 There are two reasons this isn't working: 这不起作用有两个原因:
id
attribute is on a different element. id
属性在另一个元素上。 id
attribute is not in the http://www.myschema.com/schema/ad/v1
namespace. id
属性不在http://www.myschema.com/schema/ad/v1
命名空间中。 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"
. 因此,要解决此问题,首先需要在Group
中添加另一个带有标签xml:"http://www.myschema.com/schema/ad/v1 ad"
字段xml:"http://www.myschema.com/schema/ad/v1 ad"
,并且该字段的结构定义需要使用带有标签的自己的字段xml:"id,attr"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.