将XML中的意外字段解析为Go中的结构体

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

Parsing Unexpected Fields in XML to a Struct using Go

问题

假设我们有一个XML文档,看起来像这样,在<item>标签上有一个意外的标签<custom1>

<item>
  <name>...</name>
  <price>...</price>
  <custom1>...</custom1>
</item>

用于解析这个XML的结构体如下所示:

type Item struct {
    Name  string `xml:"name"`
    Price string `xml:"price"`
}

由于我没有在结构体中包含Custom1,因此我不期望它存在。然而,是否有可能捕获剩余的标签或<item>的原始表示并放入Item结构体中?

英文:

Lets say we have an XML document that looks like this, which has an unexpected tag &lt;custom1&gt; on &lt;item&gt;

&lt;item&gt;
  &lt;name&gt;...&lt;/name&gt;
  &lt;price&gt;...&lt;/price&gt;
  &lt;custom1&gt;...&lt;/custom1&gt;
&lt;/item&gt;

The struct to parse this looks like this

type Item struct {
    Name     string   `xml:&quot;name&quot;`
    Price    string   `xml:&quot;price&quot;`
}

I don't have Custom1 in there since I'm not expecting it. However, is it possible to capture the remaining tags OR the raw representation of the &lt;item&gt; inside the Item struct?

答案1

得分: 2

使用带有,innerxml标签的字段:

type Item struct {
    Name  string `xml:"name"`
    Price string `xml:"price"`
    Other string `xml:",innerxml"`
}

Playground: https://play.golang.org/p/Io2CDjSiwx.

英文:

Use a field with ,innerxml tag:

type Item struct {
	Name  string `xml:&quot;name&quot;`
	Price string `xml:&quot;price&quot;`
	Other string `xml:&quot;,innerxml&quot;`
}

Playground: https://play.golang.org/p/Io2CDjSiwx.

huangapple
  • 本文由 发表于 2017年8月25日 05:28:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/45871175.html
匿名

发表评论

匿名网友

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

确定