Parsing XML via Golang with DTO Pattern

Hello everyone, In this tutorial, I am going to show to you how to parse XML file via Golang with DTO.

Project Structure

Books.xml

XML file contains data such as author, title and price for each book.

We don’t need an extra library to parse xml or json with Go. There are many useful packages that come with Go.

Let’s get started coding.

First, we open the file with the Open function included in the os package. We use the Defer method to close the file after we are done with it. Note that methods declared with defer will be executed just before the main function ends.

file, err := os.Open(“./books.xml”)
defer file.Close()

After that using ioutil we can convert those files into a byte array. ioutil is a package which implements input-output utility functions.

data, _ := ioutil.ReadAll(file)

Data Transfer Object

Our Data Transfer Object has two struct type. First one is called that Catalog. It can be contain all Books. Other one is called that Book. It has been store each book data.

Unmarshal

“Unmarshal parses the XML-encoded data and stores the result in the value pointed to by v, which must be an arbitrary struct, slice, or string. Well-formed data that does not fit into v is discarded.”

var catalog dto.Catalog
xml.Unmarshal(data, &catalog)

Retrieve Values

for i:=0; i < len(catalog.Books); i++{
book := catalog.Books[i]
fmt.Println(book.GetTitle())
}

If you want to check code, repository from here.

Thanks.

Software Developer mackolik

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store