Working with XML in Go (Golang): A Detailed Guide to the encoding/xml Package
In modern Go (Golang) development, the task of processing XML data is quite common — from integrating with legacy systems to data exchange in SOAP services. The Go standard library provides a powerful and flexible package encoding/xml, which allows you to efficiently parse, create, and transform XML documents. In this article, we will thoroughly examine all the key capabilities of working with XML in Go.
Key Features of the encoding/xml Package
The encoding/xml package implements a simple interface for serializing (marshaling) Go structures into XML and deserializing (unmarshaling) XML back into structures. It supports:
- Converting Go structures to XML documents and back
- Working with attributes, nested elements, and namespaces
- Streaming parsing of large XML files via
xml.Decoder - Customizable serialization rules using struct tags
Installation and Importing the Package
The encoding/xml package is part of the Go standard library, so no additional installation is required. To use it, simply import it:
import ( "encoding/xml" "fmt" "os")Marshaling: Go Structure → XML
To convert a Go structure to XML, use the xml.Marshal() function or xml.MarshalIndent() for formatted output. Consider the following example:
type Person struct { XMLName xml.Name `xml:"person"` ID int `xml:"id,attr"` FirstName string `xml:"name>first"` LastName string `xml:"name>last"` Age int `xml:"age"`}
func main() { p := Person{ ID: 123, FirstName: "Ivan", LastName: "Petrov", Age: 30, }
output, err := xml.MarshalIndent(p, "", " ") if err != nil { fmt.Printf("Marshaling error: %v", err) return }
fmt.Println(string(output))}Execution result:
<person id="123"> <name> <first>Ivan</first> <last>Petrov</last> </name> <age>30</age></person>Unmarshaling: XML → Go Structure
The reverse process — converting XML data into a Go structure — is performed using xml.Unmarshal():
func unmarshalExample() { xmlData := `<person id="456"> <name> <first>Maria</first> <last>Sidorova</last> </name> <age>25</age></person>`
var p Person err := xml.Unmarshal([]byte(xmlData), &p) if err != nil { fmt.Printf("Unmarshaling error: %v", err) return }
fmt.Printf("ID: %d, Name: %s %s, Age: %d", p.ID, p.FirstName, p.LastName, p.Age) // Output: ID: 456, Name: Maria Sidorova, Age: 25}Working with Attributes and Nested Elements
The encoding/xml package uses struct tags to control mapping. The main tag directives are:
xml:"name"— element namexml:"name,attr"— element attributexml:"parent>child"— nested elementxml:",chardata"— text contentxml:",innerxml"— raw XML inside the elementxml:",comment"— XML commentxml:"-"— ignore the field
Streaming Parsing of Large XML Files
For processing large XML documents (e.g., files gigabytes in size), the streaming parser xml.Decoder is used. This allows you to avoid loading the entire document into memory and process it element by element.