'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 :
<RootNode>
<ElementB>...</ElementB>
<ElementA>...</ElementA>
<ElementA>...</ElementA>
<ElementC>...</ElementC>
<ElementB>...</ElementB>
<ElementA>...</ElementA>
<ElementB>...</ElementB>
</RootNode>
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 ?
You can use xml:",any"
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:",any"`
}
type Element struct {
XMLName xml.Name
}
More on xml:",any"
and XMLName
here.
Playground example: http://play.golang.org/p/Vl9YI8GG1E
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With