如何在Golang中遍历XML数据?

Pra*_*ant 13 xml go

我使用xml.UnMarshal方法来获取struct对象,但它有自己的局限性.我需要一种方法,我可以在节点内获取特定类型的所有后代,而无需指定确切的xpath.

例如,我有一个以下格式的xml数据:

<content>
    <p>this is content area</p>
    <animal>
        <p>This id dog</p>
        <dog>
           <p>tommy</p>
        </dog>
    </animal>
    <birds>
        <p>this is birds</p>
        <p>this is birds</p>
    </birds>
    <animal>
        <p>this is animals</p>
    </animal>
</content>
Run Code Online (Sandbox Code Playgroud)

现在我想遍历上面的xml并按顺序处理每个节点及其子节点.问题是这种结构不固定,元素的顺序可能会改变.所以我需要一种方法让我可以穿越

While(Content.nextnode())
{
   switch(type of node)
   {
      //Process the node or traverse the child node deeper
   }
}
Run Code Online (Sandbox Code Playgroud)

Ain*_*r-G 24

您可以encoding/xml使用递归结构和简单的walk函数来使用vanilla 来实现:

type Node struct {
    XMLName xml.Name
    Content []byte `xml:",innerxml"`
    Nodes   []Node `xml:",any"`
}

func walk(nodes []Node, f func(Node) bool) {
    for _, n := range nodes {
        if f(n) {
            walk(n.Nodes, f)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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


编辑:这是一个带有attrs的版本:

type Node struct {
    XMLName xml.Name
    Attrs   []xml.Attr `xml:"-"`
    Content []byte     `xml:",innerxml"`
    Nodes   []Node     `xml:",any"`
}

func (n *Node) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
    n.Attrs = start.Attr
    type node Node

    return d.DecodeElement((*node)(n), &start)
}
Run Code Online (Sandbox Code Playgroud)

游乐场:https://play.golang.org/p/d9BkGclp-1.

  • 聪明的递归结构,也只有+1使用标准的lib. (4认同)
  • 太好了,属性呢? (2认同)

Umb*_*ndi 0

由于您要求一个库,并且您似乎想遍历 XML 树,因此我可以推荐XMLDom-Go,我在过去的一些项目中使用过它。