Parsing XML in golang

Posted by Bojidar Yankov on 05-11-2024

Parsing XML in golang



The data

We are using a part of the w3schools cd sample xml data - https://www.w3schools.com/xml/cd_catalog.xml

<CATALOG>
  <CD>
    <TITLE>Empire Burlesque</TITLE>
    <ARTIST>Bob Dylan</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Columbia</COMPANY>
    <PRICE>10.90</PRICE>
    <YEAR>1985</YEAR>
  </CD>
  <CD>
    <TITLE>Hide your heart</TITLE>
    <ARTIST>Bonnie Tyler</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>CBS Records</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1988</YEAR>
  </CD>
  <CD>
    <TITLE>Greatest Hits</TITLE>
    <ARTIST>Dolly Parton</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>RCA</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1982</YEAR>
  </CD>
</CATALOG>

The code

Below is a simple code to unmarshal the xml data into a golang struct and print the data:

package main

import (
	"encoding/xml"
	"fmt"
)

var xmlString = `
<CATALOG>
  <CD>
    <TITLE>Empire Burlesque</TITLE>
    <ARTIST>Bob Dylan</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Columbia</COMPANY>
    <PRICE>10.90</PRICE>
    <YEAR>1985</YEAR>
  </CD>
  <CD>
    <TITLE>Hide your heart</TITLE>
    <ARTIST>Bonnie Tyler</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>CBS Records</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1988</YEAR>
  </CD>
  <CD>
    <TITLE>Greatest Hits</TITLE>
    <ARTIST>Dolly Parton</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>RCA</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1982</YEAR>
  </CD>
</CATALOG>
`

type CD struct {
	Title   string  `xml:"TITLE"`
	Artist  string  `xml:"ARTIST"`
	Country string  `xml:"COUNTRY"`
	Company string  `xml:"COMPANY"`
	Price   float32 `xml:"PRICE"`
	Year    int32   `xml:"YEAR"`
}

type Catalog struct {
	CDs []CD `xml:"CD"`
}

func main() {
	var catalog Catalog

	xml.Unmarshal([]byte(xmlString), &catalog)
	for _, cd := range catalog.CDs {
		fmt.Println("----------------")
		fmt.Printf("Title: %s\n", cd.Title)
		fmt.Printf("Artist: %s\n", cd.Artist)
		fmt.Printf("Country: %s\n", cd.Country)
		fmt.Printf("Company: %s\n", cd.Company)
		fmt.Printf("Price: %f\n", cd.Price)
		fmt.Printf("Year: %d\n", cd.Year)
	}
}

Output

----------------
Title: Empire Burlesque
Artist: Bob Dylan
Country: USA
Company: Columbia
Price: 10.900000
Year: 1985
----------------
Title: Hide your heart
Artist: Bonnie Tyler
Country: UK
Company: CBS Records
Price: 9.900000
Year: 1988
----------------
Title: Greatest Hits
Artist: Dolly Parton
Country: USA
Company: RCA
Price: 9.900000
Year: 1982

Tools for converting XML schema to go structs

There are a couple of good converters, some of them are: