1

Is it feasible to match either tag of a XML file to the field of a struct in encoding/xml package in Go?

For example, in the following XML file:

<person>
    <food type="fruit" />
    <furniture type="refrigerator" />
    <food type="vegetable" />
    <food type="fruit" />
<person>

Can I get food and furniture within the same person field with the respective order?

So what I want to get is as follows:

main.Person{main.Food{Type:"fruit"}, main.Furniture{Type:"refrigerator"}, main.Food{Type:"vegetable"}, main.Food{Type:"fruit"}}

instead of

main.Person{Food:[]main.Food{main.Food{Type:"fruit"}, main.Food{Type:"vegetable"}, main.Food{Type:"fruit"}}, Furniture:[]main.Furniture{main.Furniture{Type:"refrigerator"}}}

This is because I have to take each item inside the person as chronological order, and the latter example sorts items only within each sub-tags. So I cannot know when the furniture tag happens in the latter, but can get in the former - 3rd in this case.

Thanks.

Blaszard
  • 30,954
  • 51
  • 153
  • 233

1 Answers1

2

This is possibly related to Does XML care about the order of elements? .

Basically, without an XSD (XML Schema Definition), you can't specify the order that XML elements are processed or presented.

If you process the XML with a valid XSD it may work.

Have a look at go-xsd.

Community
  • 1
  • 1
Intermernet
  • 18,604
  • 4
  • 49
  • 61