如何遍历Golang中的XML数据? [英] How to traverse through XML data in Golang?

查看:114
本文介绍了如何遍历Golang中的XML数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have used xml.UnMarshal method to get a struct object but it has it's own limitations. I need a way where I can get all the descendants of a particular type inside a node without specifying the exact xpath.

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

For example, I have an xml data of the following format:

<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>

现在我想遍历上面的xml并按照该顺序处理每个节点和它的子节点。问题是这个结构不固定,元素的顺序可能会改变。所以我需要一种方法,以便像

Now I want to traverse through the above xml and process each node and it's children in that order. The problem is that this structure is not fixed and order of elements may change. So I need a way so that I can traverse like

While(Content.nextnode())
{
   switch(type of node)
   {
      //Process the node or traverse the child node deeper
   }
}


推荐答案

您可以使用vanilla encoding / xml 通过使用递归结构和简单的漫游功能:

You can do it with a vanilla encoding/xml by using a recursive struct and a simple walk function:

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)
        }
    }
}

Playground示例: http://play.golang.org/p/rv1LlxaHvK

Playground example: http://play.golang.org/p/rv1LlxaHvK.

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

Here's a version with 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)
}

Playground: https://play.golang.org/p/d9BkGclp-1

Playground: https://play.golang.org/p/d9BkGclp-1.

这篇关于如何遍历Golang中的XML数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆