Created
July 9, 2014 14:21
-
-
Save jbarber/10cbb89a2196fdc83fba to your computer and use it in GitHub Desktop.
Example of parsing XML in Go, including extracting attributes
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 ( | |
"encoding/xml" | |
"log" | |
"strings" | |
) | |
type document struct { | |
Title string `xml:"title"` | |
Text string `xml:"text"` | |
Link link `xml:"link>url,attr"` | |
} | |
type link struct { | |
Url string `xml:"url,attr"` | |
} | |
func main() { | |
doc := `<doc><title>Hello</title><text>Some text</text><link url="http://www.example.com">A link</link></doc>` | |
decoded := document{} | |
p := xml.NewDecoder(strings.NewReader(doc)) | |
err := p.Decode(&decoded) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Println(decoded) | |
} |
Seems like it's a known issue in Go that is unlikely to be fixed:
golang/go#3688
I don't know what version of go I wrote this with originally (in 2014!) - but I'm pretty sure it would have worked then.
package main
import (
"encoding/xml"
"log"
)
type document struct {
Title string `xml:"title"`
Text string `xml:"text"`
Link link `xml:"link"`
}
type link struct {
Val string `xml:",cdata"`
Url string `xml:"url,attr"`
}
func main() {
xmlAsString := `
<doc>
<title>Hello</title>
<text>Some text</text>
<link url="http://www.example.com">A link</link>
</doc>
`
xmlAsStruct := document{}
if err := xml.Unmarshal([]byte(xmlAsString), &xmlAsStruct); err != nil {
log.Fatal(err)
}
log.Printf("%#v", xmlAsStruct)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
xml: link>url chain not valid with attr flag
go version 1.22