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

How to Efficiently Traverse XML Data in Golang?

DDD
Release: 2024-11-29 12:23:13
Original
841 people have browsed it

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)
        }
    }
}
Copy after login

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>
Copy after login

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
    }
    Copy after login
  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
    })
    Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template