在Go中具有交替内容类型的Unmarshal XML元素

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

我正在尝试解组这样的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"`
}

问题:可以使用字段TranslationNumerusForms。如果同时使用此处所示的两个选项,则会发生错误:

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

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

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

有关完整的可运行代码,请参阅this go playground

旁注:我正在尝试解析Qt Linguist TS file。该示例已被大量剥离,以使其更易于推理。

xml go unmarshalling
1个回答
0
投票
不需要实现自定义拆组器逻辑的一种简单解决方案是创建一个具有2个字段的Translation结构:1用于可选的文本内容,而一个用于可选的<numerusform>子元素:
© www.soinside.com 2019 - 2024. All rights reserved.