在 Go 中使用交替内容类型解组 XML 元素

我正在尝试像这样解组一段 xml:


<message numerus="yes">

    <source>%n part(s)</source>

    <translation>

        <numerusform>%n part</numerusform>

        <numerusform>%n parts</numerusform>

    </translation>

</message>


<message>

    <source>Foo</source>

    <translation>Bar</translation>

</message>

请注意,<translation>标签可以包含一个简单的字符串或多个<numerusform>标签。


使用 go 的 xml 包,我要解组的结构如下所示:


type Message struct {

    Source       string   `xml:"source"`

    Numerus      string   `xml:"numerus,attr"`

    Translation  string   `xml:"translation"`

    NumerusForms []string `xml:"translation>numerusform"`

}

问题:要么字段Translation要么NumerusForms可以用。如果像此处所示同时使用两者,则会发生错误:


Error on unmarshalling xml: main.Message field "Translation" with tag "translation" conflicts with field "NumerusForms" with tag "translation>numerusform"

非常合理,因为解组器无法决定如何处理<translation>标签。


有什么办法可以处理这个问题吗?可以有两个不同的命名字段(一个用于纯字符串,一个用于字符串列表,如上面所示的结构)。

摇曳的蔷薇
浏览 84回答 1
1回答

12345678_0001

一种不需要实现自定义解组器逻辑的简单解决方案是创建一个Translation具有 2 个字段的结构:1 个用于可选文本内容,1 个用于可选<numerusform>子元素:type Message struct {&nbsp; &nbsp; Source&nbsp; &nbsp; &nbsp; string&nbsp; &nbsp; &nbsp; `xml:"source"`&nbsp; &nbsp; Numerus&nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; &nbsp; `xml:"numerus,attr"`&nbsp; &nbsp; Translation Translation `xml:"translation"`}type Translation struct {&nbsp; &nbsp; Content&nbsp; &nbsp; &nbsp; string&nbsp; &nbsp;`xml:",cdata"`&nbsp; &nbsp; NumerusForms []string `xml:"numerusform"`}这将输出(在Go Playground上尝试):Source: %n part(s)Numerus: yesTranslation: "\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t"NumerusForms: [%n part %n parts]&nbsp; Numerus: %n part&nbsp; Numerus: %n partsSource: FooNumerus:&nbsp;Translation: "Bar"NumerusForms: []请注意,当实际存在<numerusform>子元素时,该Translation.Content字段仍然会填充缩进字符,您可以安全地忽略这些字符。
打开App,查看更多内容
随时随地看视频慕课网APP