arrays - 在 go 中解析简单值的 xml 数组

标签 arrays xml go slice

我有一个如下所示的 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 值,而不是通常的键/值对。

最佳答案

您需要指定 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 中提到了此功能:

  • 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 ">".

关于arrays - 在 go 中解析简单值的 xml 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38600388/

相关文章:

xml - 哪些字符永远不能出现在 URL 中?

go - Go 的递归函数调用是尾优化的吗?

pointers - 将 *[]foo 类型的变量转换为 *[]bar

javascript - 在 Javascript 中将字符串转换为数组的数组

Java 数组 字符串

c++ - (C++) 试图完成一个快速程序,但我不确定哪里出错了?

go - 如何从 exec.StdoutPipe() 获得输出的颜色?

python - reshape 和堆叠 2D 阵列以形成 3D 阵列

javascript - AJAX:帮助让 xml 显示在 html 中

java - Java中如何修改XML标签?