How to Parse XML in Go with encoding/xml

Parse XML in Go by defining a struct with xml tags and calling encoding/xml.Unmarshal on the raw data.

Use encoding/xml.Unmarshal to decode XML bytes into a Go struct that mirrors the XML hierarchy.

package main

import (
	"encoding/xml"
	"fmt"
	"log"
)

type Book struct {
	XMLName xml.Name `xml:"book"`
	Title   string   `xml:"title"`
	Author  string   `xml:"author"`
}

func main() {
	data := []byte(`
	<book>
		<title>Go in Action</title>
		<author>William Kennedy</author>
	</book>`)

	var b Book
	if err := xml.Unmarshal(data, &b); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Title: %s, Author: %s\n", b.Title, b.Author)
}