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 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思