← Home

XML unmarshal example with Golang

Golang is quite a remarkable language. It is not verbose and we can happily write good code with it.

You should check for Golang Specification and for Effective Go in case you want to know more about the language.

For now, I will restrain myself with this simple example for XML unmarshall in Golang.

First of all, let’s start with this XML example from W3Schools:

<?xml version="1.0" encoding="utf-8" ?>	
<notebook>
	<note>
		<to>Tove</to>
		<from>Jani</from>
		<heading>Reminder</heading>
		<body>Don't forget me this weekend!</body>
	</note>
</notebook>

To unmarshal it in go we will have to setup a struct type for each node so we can catch all data correctly:

type Notebook struct {
	XMLName xml.Name `xml:"notebook"`
	Notes   []Note   `xml:"note"`
}

type Note struct {
	XMLName xml.Name `xml:"note"`
	To      string   `xml:"to"`
	From    string   `xml:"from"`
	Heading string   `xml:"heading"`
	Body    string   `xml:"body"`
}

With the types setup, reading the XML into it is quite simple: we should define a new data holder, in our case xmlData, and it’s reference will be passed to the XML Unmarshal.

xmlData := Notebook{}
err := xml.Unmarshal([]byte(xmlTest), &xmlData)
if err != nil {
	fmt.Println("error on unmarshalling")
}

For a complete example reference, check below:

package main

import (
	"encoding/xml"
	"fmt"
)

type Notebook struct {
	XMLName xml.Name `xml:"notebook"`
	Notes   []Note   `xml:"note"`
}

type Note struct {
	XMLName xml.Name `xml:"note"`
	To      string   `xml:"to"`
	From    string   `xml:"from"`
	Heading string   `xml:"heading"`
	Body    string   `xml:"body"`
}

func main() {

	xmlTest := `
<?xml version="1.0" encoding="utf-8" ?>	
<notebook>
	<note>
		<to>Tove</to>
		<from>Jani</from>
		<heading>Reminder</heading>
		<body>Don't forget me this weekend!</body>
	</note>
</notebook>
	`

	xmlData := Notebook{}
	err := xml.Unmarshal([]byte(xmlTest), &xmlData)
	if err != nil {
		fmt.Println("error on unmarshalling")
	}

	fmt.Println(xmlData)
}