Home >Backend Development >Golang >How to Efficiently Traverse XML Data in Golang?

How to Efficiently Traverse XML Data in Golang?

DDD
DDDOriginal
2024-11-29 12:23:13924browse

How to Efficiently Traverse XML Data in Golang?

Traversing XML Data in Golang

To traverse through XML data in Golang, one can utilize a vanilla encoding/xml approach by constructing a recursive struct and employing a walk function.

Struct Definition and 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)
        }
    }
}

Example Usage

Consider the following 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>

To traverse the XML and process each node and its children:

  1. Unmarshal the XML into a struct:

    var content Node
    if err := xml.Unmarshal(xmlData, &content); err != nil {
     // handle error
    }
  2. Walk through the struct using the walk function:

    walk(content.Nodes, func(n Node) bool {
     // Process the node or traverse its child nodes here
     fmt.Printf("Node: %s\n", n.XMLName.Local)
     return true
    })

Enhanced Version with Attributes

For nodes with attributes, here's an enhanced version:

type Node struct {
    XMLName xml.Name
    Attrs   []xml.Attr `xml:",any,attr"`
    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)
}

This allows accessing attributes within the node processing logic.

The above is the detailed content of How to Efficiently Traverse XML Data in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn