【问题标题】:How to map an xml sequence of mixed elements to a go struct?如何将混合元素的 xml 序列映射到 go 结构?
【发布时间】:2015-05-02 19:14:32
【问题描述】:

正在尝试加载一个 XML 文件,该文件包含无限的混合元素序列(XSD 中序列中的选择) 文件看起来像这样:

<RootNode>
    <ElementB>...</ElementB>
    <ElementA>...</ElementA>
    <ElementA>...</ElementA>
    <ElementC>...</ElementC>
    <ElementB>...</ElementB>
    <ElementA>...</ElementA>
    <ElementB>...</ElementB>
</RootNode>

我使用 xml.Unmarshal 来初始化和填充这些结构:

type RootNode struct {
    ElementA []ElementA
    ElementB []ElementB
    ElementC []ElementC
}

type ElementA struct {
}

type ElementB struct {
}

type ElementC struct {
}

我在这里有工作示例http://play.golang.org/p/ajIReJS35F。 问题是我需要知道原始序列中元素的索引。有了这个描述,这个信息就丢失了。

有没有办法在同一个数组中加载 ElementA、ElementB 或 ElementC 类型的元素?更一般地说,将混合元素列表映射到 go 结构的最佳方法是什么?

【问题讨论】:

    标签: xml go sequence choice


    【解决方案1】:

    您可以在根节点上使用xml:",any" 标签,然后将其余部分解组为具有XMLName 字段的结构,如下所示:

    type RootNode struct {
        Elements []Element `xml:",any"`
    }
    
    type Element struct {
        XMLName xml.Name
    }
    

    更多关于xml:",any"XMLNamehere

    游乐场示例:http://play.golang.org/p/Vl9YI8GG1E

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      相关资源
      最近更新 更多