【问题标题】:Unmarshal XML element with alternating content type in Go在 Go 中解组具有交替内容类型的 XML 元素
【发布时间】:2019-12-05 09:37:32
【问题描述】:

我正在尝试像这样解组一段 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>

请注意&lt;translation&gt; 标签可以包含一个简单的字符串或多个&lt;numerusform&gt; 标签。

使用 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"

非常合理,因为解组器无法决定如何处理&lt;translation&gt; 标签。

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

完整的可运行代码请参考this go playground

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

【问题讨论】:

    标签: xml go unmarshalling


    【解决方案1】:

    一种不需要实现自定义解组器逻辑的简单解决方案是创建一个具有 2 个字段的 Translation 结构:1 个用于可选文本内容,一个用于可选 &lt;numerusform&gt; 子元素:

    type Message struct {
        Source      string      `xml:"source"`
        Numerus     string      `xml:"numerus,attr"`
        Translation Translation `xml:"translation"`
    }
    
    type Translation struct {
        Content      string   `xml:",cdata"`
        NumerusForms []string `xml:"numerusform"`
    }
    

    这将输出(在Go Playground 上尝试):

    Source: %n part(s)
    Numerus: yes
    Translation: "\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t"
    NumerusForms: [%n part %n parts]
      Numerus: %n part
      Numerus: %n parts
    
    Source: Foo
    Numerus: 
    Translation: "Bar"
    NumerusForms: []
    

    请注意,当实际存在 &lt;numerusform&gt; 子元素时,Translation.Content 字段仍会填充缩进字符,您可以放心忽略。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      相关资源
      最近更新 更多