Sample XML File
In this example, we will use the example XML file as provided below. Feel free to copy the contents and experiment with it yourself.
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
</book>
</catalog>
The previous example contains a catalog of various books with nested elements, such as author, title, genre, and more.
Imports
The first step is to import the required package. For this tutorial, we need the os package to read files and the encoding/XML package to parse XML files:
"os"
"fmt"
"os"
)
Once imported, we can get started.
Golang Read XML File
Let us start by reading our XML file. We can do this using the Open method from the os package. An example code is as shown below:
import (
"log"
"os"
)
funcmain() {
// open xml
file, err := os.Open("books.xml")
if err != nil {
log.Fatal(err)
}
deferfile.Close()
}
Defining Structures
To parse XML, we will need to make use of Golang structures. We can create one to represent the book catalog from the XML file.
The following example provides the book construct.
The resulting code is as shown:
XMLNamexml.Name `xml:"book"`
Author string `xml:"author"`
Title string `xml."title"`
Genre string `xml."genre"`
Price float64 `xml."price"`
PublishData string `xml."publish_date"`
Description string `xml."description"`
}
Golang Marshals XML
The next step is to marshal the XML data. Hence, we need to convert the data into byte array. We can do this using the code provided below:
var books Books
xml.Unmarshal(b_ARR, &books)
Now that the XML information is stored in the struct, you can reference the fields to get the value.
Conclusion
This article was a tutorial on parsing XML files using the encoding/XML package. We discussed the basics, the imports, reading the XML file, defining the structures, and how Golang marshals the XML data. We hope you found this article helpful. Check out other Linux Hint articles for more tips and information.