如何将一个包含混合元素的 XML 序列映射到 Go 结构体?

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

How to map an xml sequence of mixed elements to a go struct?

问题

我正在尝试加载一个包含无限序列的混合元素的XML文件(XSD中序列中的选择)。
文件的结构如下:

<RootNode>
    <ElementB>...</ElementB>
    <ElementA>...</ElementA>
    <ElementA>...</ElementA>
    <ElementC>...</ElementC>
    <ElementB>...</ElementB>
    <ElementA>...</ElementA>
    <ElementB>...</ElementB>
</RootNode>

我使用xml.Unmarshal来初始化和填充这些结构体:

type RootNode struct {
    ElementA []ElementA
    ElementB []ElementB
    ElementC []ElementC
}

type ElementA struct {
}

type ElementB struct {
}

type ElementC struct {
}

我在这里有一个工作示例:http://play.golang.org/p/ajIReJS35F。
问题是我需要知道原始序列中元素的索引。但是根据这个描述,这个信息丢失了。

有没有办法将类型为ElementA、ElementB或ElementC的元素加载到同一个数组中?更一般地说,将混合元素列表映射到Go结构的最佳方法是什么?

英文:

'm trying to load an XML file that contains an unbounded sequence of mixed elements (a choice in a sequence in the XSD)
The file looks like that :

&lt;RootNode&gt;
    &lt;ElementB&gt;...&lt;/ElementB&gt;
    &lt;ElementA&gt;...&lt;/ElementA&gt;
    &lt;ElementA&gt;...&lt;/ElementA&gt;
    &lt;ElementC&gt;...&lt;/ElementC&gt;
    &lt;ElementB&gt;...&lt;/ElementB&gt;
    &lt;ElementA&gt;...&lt;/ElementA&gt;
    &lt;ElementB&gt;...&lt;/ElementB&gt;
&lt;/RootNode&gt;

I use xml.Unmarshal to initialize and fill these structs :

type RootNode struct {
    ElementA []ElementA
    ElementB []ElementB
    ElementC []ElementC
}

type ElementA struct {
}

type ElementB struct {
}

type ElementC struct {
}

I have working exemple here http://play.golang.org/p/ajIReJS35F.
The problem is that i need to know the index of the elements in the original sequence. And with that description, this info is lost.

Is there a way to to load elements of type ElementA, ElementB or ElementC in the same array ? More generally, what is the best way to map a list of mixed elements to a go struct ?

答案1

得分: 5

你可以在根节点上使用xml:",any"标签,然后将其余部分解组为具有XMLName字段的结构体,如下所示:

type RootNode struct {
    Elements []Element `xml:",any"`
}

type Element struct {
    XMLName xml.Name
}

关于xml:",any"XMLName的更多信息,请参考这里

Playground示例:http://play.golang.org/p/Vl9YI8GG1E

英文:

You can use xml:&quot;,any&quot; tag on your root node and then unmarshal the rest into structs that have an XMLName field like this:

type RootNode struct {
	Elements []Element `xml:&quot;,any&quot;`
}

type Element struct {
	XMLName xml.Name
}

More on xml:&quot;,any&quot; and XMLName here.

Playground example: http://play.golang.org/p/Vl9YI8GG1E

huangapple
  • 本文由 发表于 2015年3月2日 20:25:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/28809738.html
匿名

发表评论

匿名网友

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

确定