我如何为元素指定一个既有属性又有内容的XML结构标签?

问题描述 投票:0回答:1

我必须解析一些东西(在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 go
1个回答
1
投票

你可以在结构上声明一个与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"`
}

https:/play.golang.compAUoKBxn1Zu5


2
投票

答案是,对于属性,你不使用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"`
}

我的直觉是,逗号分隔的列表中的所有内容都是关键字(比如说: attromitempty),所以我没有想到会有一个ID(如 KEY)要在那里表达,但我的直觉是不正确的。关于这个问题的更多讨论是 此处.

编辑: 我说的太早了. 上面没有取FirstKey和SecondKey的值。

© www.soinside.com 2019 - 2024. All rights reserved.