Skip to content

Instantly share code, notes, and snippets.

@dossy
Last active March 16, 2018 11:18
Show Gist options
  • Save dossy/9811dc9f554d7b455220d1bfb86b9d1c to your computer and use it in GitHub Desktop.
Save dossy/9811dc9f554d7b455220d1bfb86b9d1c to your computer and use it in GitHub Desktop.
General-purpose XML parsing in Go
/*
https://play.golang.org/p/3g50cX2ed-
Output looks like:
&main.Node{XMLName:xml.Name{Space:"", Local:"foo"}, Comments:" a b ", Attrs:[]xml.Attr(nil), Value:"", Children:[]main.Node{main.Node{XMLName:xml.Name{Space:"", Local:"bar"}, Comments:"", Attrs:[]xml.Attr{xml.Attr{Name:xml.Name{Space:"", Local:"baz"}, Value:"bing"}}, Value:"", Children:[]main.Node(nil)}}}
*/
package main
import (
"encoding/xml"
"fmt"
)
type Node struct {
XMLName xml.Name
Comments string `xml:",comment"`
Attrs []xml.Attr `xml:",any,attr"`
Value string "chardata"
Children []Node `xml:",any"`
}
func main() {
doc := new(Node)
xml.Unmarshal([]byte(`<foo><!-- a --><bar baz="bing">quux</bar><!-- b --></foo>`), doc)
fmt.Printf("%#v\n", doc)
}
@kevsersrca
Copy link

Hi. I was having trouble getting value. "chardata"instead of `xml:",chardata"` fixed when I use it like this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment