Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

'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 ?

like image 979
failed onceagain Avatar asked Sep 29 '22 15:09

failed onceagain


1 Answers

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

like image 60
Ainar-G Avatar answered Oct 03 '22 03:10

Ainar-G