XML Data Traversal in Go
Problem:
XML data often presents challenges when it comes to accessing specific elements without prior knowledge of their XPath. The xml.Unmarshal method has limitations in this regard, requiring users to specify exact paths to obtain data.
Solution:
To traverse through XML data flexibly, we can utilize a recursive data structure alongside a simple walk function.
Recursive Data Structure:
type Node struct { XMLName xml.Name Content []byte `xml:",innerxml"` Nodes []Node `xml:",any"` }
In this structure, each Node represents an element in the XML document, containing its name, inner XML content (for non-nested elements), and a slice of children nodes.
Walk Function:
func walk(nodes []Node, f func(Node) bool) { for _, n := range nodes { if f(n) { walk(n.Nodes, f) } } }
The walk function recursively traverses through the Node tree, calling the provided function f for each encountered node.
Usage:
To traverse through an XML document and process its elements accordingly:
Example:
The following code traverses the XML document in the question, printing the element names in order:
content := Node{} if err := xml.Unmarshal([]byte(rawXML), &content); err != nil { // Handle error } walk(content.Nodes, func(n Node) bool { fmt.Println(n.XMLName.Local) return true })
Output:
content p animal p dog p birds p p animal p
The above is the detailed content of How Can I Efficiently Traverse XML Data in Go Without Using XPath?. For more information, please follow other related articles on the PHP Chinese website!