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.
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) } } }
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:
Unmarshal the XML into a struct:
var content Node if err := xml.Unmarshal(xmlData, &content); err != nil { // handle error }
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 })
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!