我必须解析一些东西(在Go程序中),看起来像。
<PARENT>
<FIRST KEY="something">Value</FIRST>
<SECOND KEY="something">Value</SECOND>
</PARENT>
我试过了
type SomeType struct {
XMLName xml.Name `xml:"PARENT"`
FirstValue string `xml:"FIRST"`
FirstKey string `xml:"FIRST>KEY,attr"`
SecondValue string `xml:"SECOND"`
FirstKey string `xml:"SECOND>KEY,attr"`
}
但我得到这个错误。
xml: FIRST>KEY chain not valid with attr flag
正确的方法是什么?
你可以在结构上声明一个与xml匹配的类型。
type T struct {
XMLName xml.Name `xml:"PARENT"`
First Value `xml:"FIRST"`
Second Value `xml:"SECOND"`
}
type Value struct {
Key string `xml:"KEY,attr"`
Value string `xml:",chardata"`
}
答案是,对于属性,你不使用ID链。而是使用逗号分隔列表中的ID,就像这样。
type SomeType struct {
XMLName xml.Name `xml:"PARENT"`
FirstValue string `xml:"FIRST"`
FirstKey string `xml:"FIRST,KEY,attr"`
SecondValue string `xml:"SECOND"`
SecondKey string `xml:"SECOND,KEY,attr"`
}
我的直觉是,逗号分隔的列表中的所有内容都是关键字(比如说: attr
或 omitempty
),所以我没有想到会有一个ID(如 KEY
)要在那里表达,但我的直觉是不正确的。关于这个问题的更多讨论是 此处.
编辑: 我说的太早了. 上面没有取FirstKey和SecondKey的值。