douqi2804 2016-07-26 21:43
浏览 65
已采纳

在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.

  • 写回答

1条回答 默认 最新

  • douhuan9289 2016-07-26 21:46
    关注

    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 ">".
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块