【问题标题】:Parse an xml array of simple values in go在 go 中解析一个简单值的 xml 数组
【发布时间】:2016-11-30 17:19:47
【问题描述】:

我有一个如下所示的 xml:

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

我发现在 go 中解析很有挑战性。我已经尝试了以下

type MyElement struct {
  Ids int[] 
}

甚至

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

type MyElement struct {
  Ids Ids
}

但它永远不会被捡起。

困难在于元素都被称为 int 并且只存储一个 int 值,而不是通常的键/值对。

【问题讨论】:

    标签: arrays xml go slice


    【解决方案1】:

    你需要指定int元素的路径:

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

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

    您也可以这样做,以免重复“Ids”

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

    xml.Unmarshal's documentation 中提到了此功能:

    • 如果 XML 元素包含名称匹配的子元素 格式为“a”或“a>b>c”的标记的前缀,解组 将下降到 XML 结构中查找具有 给定名称,并将最里面的元素映射到该结构 场地。以“>”开头的标签相当于一个开头 字段名称后跟“>”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多