在Go中解析简单值的xml数组

I have an xml that looks like this:

<MyElement>
    <Ids>
        <int>1</int>
        <int>2</int>
    </Ids>
</MyElement>

I find it challenging to parse in go. I've tried the following

type MyElement struct {
  Ids int[] 
}

or even

type Ids struct {
  id int[] `xml:"int"`
}

type MyElement struct {
  Ids Ids
}

But it never get picked up.

The difficulty is in the fact that the elements are all called int and only store an int value, instead of the usual key/value pair.

You need to specify the path the int elements:

type MyElement struct {
    Ids []int `xml:"Ids>int"`
}

https://play.golang.org/p/HfyQzOiSqa

You can also do this in order not to repeat "Ids"

type MyElement struct {
    Ids []int `xml:">int"`
}

This functionality is mentioned in xml.Unmarshal's documentation:

  • If the XML element contains a sub-element whose name matches the prefix of a tag formatted as "a" or "a>b>c", unmarshal will descend into the XML structure looking for elements with the given names, and will map the innermost elements to that struct field. A tag starting with ">" is equivalent to one starting with the field name followed by ">".