在 go 中解析一个 xml 简单值数组
Parse an xml array of simple values in go
我有一个 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 值,而不是通常的 key/value 对。
您需要指定 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 ">".
我有一个 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 值,而不是通常的 key/value 对。
您需要指定 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 ">".