Created
November 18, 2011 17:59
-
-
Save chrisfarms/1377218 to your computer and use it in GitHub Desktop.
Really rough example of using xml.Parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
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
Hello~ Why I code it hits: could not import xml (no required module provides package "xml")?