在Go语言中解析XML。

huangapple go评论100阅读模式
英文:

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)
}

Play

英文:

I'm trying to decode the following xml. For some reasons I can't decode the Id

package main

import (
    &quot;encoding/xml&quot;
    &quot;fmt&quot;
)

var data = `
&lt;g xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot; xmlns:ad=&quot;http://www.myschema.com/schema/ad/v1&quot;&gt;
    &lt;a xlink:href=&quot;http://example.com&quot; data-bind=&quot;121&quot;&gt;lala&lt;/a&gt;
    &lt;ad:ad id=&quot;1060469006&quot;&gt;
&lt;/g&gt;
`

type Anchor struct {
    DataBind  int    `xml:&quot;data-bind,attr&quot;`  
    XlinkHref string `xml:&quot;http://www.w3.org/1999/xlink href,attr&quot;`
    Id int  `xml:&quot;http://www.myschema.com/schema/ad/v1 id,attr&quot;` 
}

type Group struct {
    A Anchor `xml:&quot;a&quot;`
}

func main() {
    group := Group{}
    _ = xml.Unmarshal([]byte(data), &amp;group)

    fmt.Printf(&quot;%#v\n&quot;, group.A)
}

Play

答案1

得分: 4

你正在解码的结构体正在寻找XML中<a>元素上的ad:id属性。这不起作用的原因有两个:

  1. id属性位于不同的元素上。
  2. 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 &lt;a&gt; element in the XML. There are two reasons this isn't working:

  1. the id attribute is on a different element.
  2. the id attribute is not in the http://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:&quot;http://www.myschema.com/schema/ad/v1 ad&quot;, and the struct definition for that field needs its own field with the tag xml:&quot;id,attr&quot;.

huangapple
  • 本文由 发表于 2014年5月8日 10:05:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/23531514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定