Sling Academy
Home/Golang/How to read and parse XML files in Go

How to read and parse XML files in Go

Last updated: November 26, 2024

Parsing XML files is a common task in many applications. Go provides a robust set of packages to handle XML files easily and efficiently. In this article, we will go over the steps to read and parse XML files in Go, using the encoding/xml package.

Prerequisites

Before we dive into the code, make sure you have Go installed on your system. You can download it from the official website if you haven't already.

Step-by-step guide to reading and parsing XML

1. Create a Go Project

First, we'll set up a new directory for our Go project. Open your terminal and run:

mkdir xmlparser && cd xmlparser

2. Initialize a Go Module

Initialize a new Go module in your project directory:

go mod init xmlparser

3. Create an XML File

For demonstration purposes, let's create a sample XML file that we will parse:

<?xml version="1.0" encoding="UTF-8"?>
<employees>
    <employee>
        <name>John Doe</name>
        <age>30</age>
        <position>Developer</position>
    </employee>
    <employee>
        <name>Jane Smith</name>
        <age>25</age>
        <position>Designer</position>
    </employee>
</employees>

4. Define Structs Matching the XML Structure

In Go, you need to define struct types that correspond to the XML structure. Create a file called main.go and add the following code:

package main

import (
    "encoding/xml"
    "fmt"
    "io/ioutil"
    "os"
)

type Employee struct {
    Name     string `xml:"name"`
    Age      int    `xml:"age"`
    Position string `xml:"position"`
}

type Employees struct {
    XMLName  xml.Name   `xml:"employees"`
    Employee []Employee `xml:"employee"`
}

5. Read and Parse the XML File

Now, let's write a function to read and parse the XML file:

func main() {
    xmlFile, err := os.Open("employees.xml")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer xmlFile.Close()

    byteValue, _ := ioutil.ReadAll(xmlFile)

    var employees Employees
    xml.Unmarshal(byteValue, &employees)

    for i := 0; i < len(employees.Employee); i++ {
        fmt.Println("Employee Name: " + employees.Employee[i].Name)
        fmt.Println("Employee Age: ", employees.Employee[i].Age)
        fmt.Println("Employee Position: " + employees.Employee[i].Position)
    }
}

This program opens the XML file, reads its content, and uses xml.Unmarshal to populate the employees variable with the data from the XML file.

Running the Program

Save the XML file created above as employees.xml in the same directory as your Go program. To run your program, execute the following command in your terminal:

go run main.go

You should see output detailing each employee's name, age, and position, demonstrating the successful parsing of the XML file.

Conclusion

Parsing XML files in Go is straightforward with the help of the encoding/xml package. By defining appropriate structs and reading the XML into them, you can efficiently extract and use data stored in XML formats.

Next Article: How to list all files and subfolders in a folder in Go

Previous Article: How to read and write JSON files in Go

Series: File I/O and Operating System Interaction

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant