gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:04:12 24 4
gpt4 key购买 nike

我有一个如下所示的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com