Created
July 9, 2012 13:26
-
-
Save suapapa/3076549 to your computer and use it in GitHub Desktop.
golang: xml unmarshal practice
This file contains hidden or 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 ( | |
"encoding/xml" | |
"fmt" | |
"log" | |
) | |
var encoded = ` | |
<list><value>a</value> | |
<list><value>b</value> | |
<list><value>c</value> | |
</list> | |
</list> | |
</list> | |
` | |
type List struct { | |
XMLName xml.Name `xml:"list"` | |
Value string `xml:"value"` | |
List *List | |
} | |
var data = `<?xml version="1.0" encoding="UTF-8" ?> | |
<info> | |
<title>My website</title> | |
<slogan>My website is your</slogan> | |
</info>` | |
type Website struct { | |
Title string `xml:"title"` | |
Slogan string `xml:"slogan"` | |
} | |
func (l *List) String() string { | |
if l == nil { | |
return "nil" | |
} | |
return l.Value + " :: " + l.List.String() | |
} | |
func main() { | |
var l *List | |
err := xml.Unmarshal([]byte(encoded), &l) | |
if err != nil { | |
log.Fatalln("xml.Unmarshal: ", err) | |
} | |
fmt.Println(l) | |
var w *Website | |
xml.Unmarshal([]byte(data), &w) | |
fmt.Printf("%#v\n", w) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment