我不知道如何使这段代码工作。我只是想像这样解析一个简单的 XML 文件:
package main
import (
"encoding/xml"
"fmt"
)
type Data struct {
XMLName xml.Name `xml:"data"`
Nam string `xml:"nam,attr"`
}
type Struct struct {
XMLName xml.Name `xml:"struct"`
Data []Data
}
func main() {
x := `
<struct>
<data nam="MESSAGE_TYPE">
</data>
<data nam="MESSAGE_TYPE2">
</data>
</struct>
`
s := Struct{}
err := xml.Unmarshal([]byte(x), &s)
if err != nil {
panic(err)
}
fmt.Printf("%v\n", s)
fmt.Println(s.Data)
}
我得到的是:
{{ struct} []}
[]
但是当我将“数据”元素更改为大写时,如下所示:
package main
import (
"encoding/xml"
"fmt"
)
type Data struct {
XMLName xml.Name `xml:"Data"`
Nam string `xml:"nam,attr"`
}
type Struct struct {
XMLName xml.Name `xml:"struct"`
Data []Data
}
func main() {
x := `
<struct>
<Data nam="MESSAGE_TYPE">
</Data>
<Data nam="MESSAGE_TYPE2">
</Data>
</struct>
`
s := Struct{}
err := xml.Unmarshal([]byte(x), &s)
if err != nil {
panic(err)
}
fmt.Printf("%v\n", s)
fmt.Println(s.Data)
}
我明白了:
{{ struct} [{{ Data} MESSAGE_TYPE} {{ Data} MESSAGE_TYPE2}]}
[{{ Data} MESSAGE_TYPE} {{ Data} MESSAGE_TYPE2}]
谁能告诉我为什么?
最佳答案
如果您没有在结构字段上放置 XML 注释,则该字段的名称将作为 XML 元素的名称。
在 Unmarshal 上的文档中在 endoding/xml 包中,我们可以找到以下内容:
Unmarshal maps an XML element to a struct using the following rules. In the rules, the tag of a field refers to the value associated with the key 'xml' in the struct field's tag (see the example above).
- If the XML element contains a sub-element whose name matches a field without any mode flags (",attr", ",chardata", etc), Unmarshal maps the sub-element to that struct field.
匹配区分大小写,因此它会影响您的大小写。
我建议像这样注释结构以适合实际数据:
type Struct struct {
XMLName xml.Name `xml:"struct"`
Data []Data `xml:"data"`
}
关于xml - 使用 Go 解析 XML,具有多个小写元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26700825/