Skip to content

Instantly share code, notes, and snippets.

@exul
Forked from suapapa/xml_unmarshal.go
Created November 6, 2023 14:26
Show Gist options
  • Save exul/9a07587cf5c424fd9c0fd6d59071ae9a to your computer and use it in GitHub Desktop.
Save exul/9a07587cf5c424fd9c0fd6d59071ae9a to your computer and use it in GitHub Desktop.
golang: xml unmarshal practice
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