Skip to content

Instantly share code, notes, and snippets.

@chrisfarms
Created November 18, 2011 17:59
Show Gist options
  • Save chrisfarms/1377218 to your computer and use it in GitHub Desktop.
Save chrisfarms/1377218 to your computer and use it in GitHub Desktop.
Really rough example of using xml.Parser
package main
import (
"fmt";
"io"
"xml"
"strings"
)
const XML = `<?xml version="1.0" encoding="UTF-8" ?>
<langs>
<en>English</en>
</langs>`
func main() {
r := strings.NewReader(XML)
m := xmlToMap(r)
fmt.Println(m)
}
func xmlToMap(r io.Reader) map[string]string {
// result
m := make(map[string]string)
// the current value stack
values := make([]string,0)
// parser
p := xml.NewParser(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 == "langs" {
continue
}
m[t.Name.Local] = values[len(values)-1]
// pop
values = values[:len(values)]
}
}
// done
return m
}
@pmtabe1
Copy link

pmtabe1 commented Oct 10, 2022

try adding import from "encoding/xml"

instead of of "xml"

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