go - How to traverse through XML data in Golang? -


i have used xml.unmarshal method struct object has it's own limitations. need way can descendants of particular type inside node without specifying exact xpath.

for example, have xml data of following format:

<content>     <p>this content area</p>     <animal>         <p>this id dog</p>         <dog>            <p>tommy</p>         </dog>     </animal>     <birds>         <p>this birds</p>         <p>this birds</p>     </birds>     <animal>         <p>this animals</p>     </animal> </content> 

now want traverse through above xml , process each node , it's children in order. problem structure not fixed , order of elements may change. need way can traverse like

while(content.nextnode()) {    switch(type of node)    {       //process node or traverse child node deeper    } } 

you can vanilla encoding/xml using recursive struct , 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) {     _, n := range nodes {         if f(n) {             walk(n.nodes, f)         }     } } 

playground example: http://play.golang.org/p/rv1llxahvk.


edit: here's version 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.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -