Skip to content

Instantly share code, notes, and snippets.

@jbarber
Created July 9, 2014 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbarber/10cbb89a2196fdc83fba to your computer and use it in GitHub Desktop.
Save jbarber/10cbb89a2196fdc83fba to your computer and use it in GitHub Desktop.
Example of parsing XML in Go, including extracting attributes
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)
}
@KacperPerschke
Copy link

xml: link>url chain not valid with attr flag
go version 1.22

@jbarber
Copy link
Author

jbarber commented May 6, 2024

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.

@KacperPerschke
Copy link

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