Skip to content

Instantly share code, notes, and snippets.

@jokaye
Last active August 11, 2017 03:01
Show Gist options
  • Select an option

  • Save jokaye/78dd5f9bbf907e9347dfdca70065de17 to your computer and use it in GitHub Desktop.

Select an option

Save jokaye/78dd5f9bbf907e9347dfdca70065de17 to your computer and use it in GitHub Desktop.
func XmlToMap(r io.Reader, root string) map[string]string {
// result
m := make(map[string]string)
// the current value stack
values := make([]string, 0)
// parser
p := xml.NewDecoder(r)
for token, err := p.Token(); err == nil; token, err = p.Token() {
switch t := token.(type) {
case xml.CharData:
// push
values = append(values, string([]byte(t)))
case xml.EndElement:
if t.Name.Local == root {
continue
}
m[t.Name.Local] = values[len(values)-1]
// pop
values = values[:len(values)]
}
}
// done
return m
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment