使用根级元素进行XML解析

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

XML parsing with a root level element

问题

可以解析根级别的XML元素吗?

这个XML没有任何包装器 <message att='Hello'/>

  1. var x = Xml{}
  2. xml.Unmarshal([]byte(`<message att='Hello'/>`), &x)
  3. fmt.Println(x)

Xml结构体

  1. type Xml struct {
  2. Message struct {
  3. Att string `xml:"att,attr"`
  4. } `xml:"message"`
  5. }
英文:

Is it possible to parse root level XML elements?

This XML is without any wrapper &lt;message att=&#39;Hello&#39;/&gt;

  1. var x = Xml{}
  2. xml.Unmarshal([]byte(`&lt;message att=&#39;Hello&#39;/&gt;`), &amp;x)
  3. fmt.Println(x)

Xml Struct

  1. type Xml struct {
  2. Message struct {
  3. Att string `xml:&quot;att,attr&quot;`
  4. } `xml:&quot;message&quot;`
  5. }

答案1

得分: 1

是的,你可以这样做。只需移除包装的 Xml 元素,并直接解组 Message

  1. type Message struct {
  2. Att string `xml:"att,attr"`
  3. }
  4. var x = Message{}
  5. err := xml.Unmarshal([]byte(`<message att='Hello'/>`), &x)
  6. if err != nil {
  7. panic(err)
  8. }
  9. fmt.Println(x)

你可以在这个链接中查看示例代码:https://play.golang.org/p/EdtaWLm6Cl

英文:

Yes, you can do this. Simply remove the wrapping Xml element and unmarshal Message directly:

  1. type Message struct {
  2. Att string `xml:&quot;att,attr&quot;`
  3. }

<!-- -->

  1. var x = Message{}
  2. err := xml.Unmarshal([]byte(`&lt;message att=&#39;Hello&#39;/&gt;`), &amp;x)
  3. if err != nil {
  4. panic(err)
  5. }
  6. fmt.Println(x)

https://play.golang.org/p/EdtaWLm6Cl

huangapple
  • 本文由 发表于 2017年3月15日 06:06:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/42797465.html
匿名

发表评论

匿名网友

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

确定