XML, or Extensible Markup Language, is a popular format for structured data representation. In Go, the `encoding/xml` package provides powerful capabilities for XML serialization and deserialization. This guide will walk you through using the `encoding/xml` package with concise examples and explanations to get you started quickly.
Installing Go
If you don't have Go installed, make sure to download it from the official website: https://golang.org/dl/. Follow the installation instructions provided for your operating system.
XML Serialization
XML serialization converts your Go data structures into XML format. Here’s how you can serialize a simple Go struct to XML:
package main
import (
"encoding/xml"
"fmt"
)
// Person defines a simple struct
type Person struct {
XMLName xml.Name `xml:"person"`
Name string `xml:"name"`
Age int `xml:"age"`
}
func main() {
p := Person{Name: "John Doe", Age: 30}
output, err := xml.MarshalIndent(p, "", " ")
if err != nil {
fmt.Printf("error: %v\n", err)
return
}
fmt.Printf("%s\n", output)
}
This code creates a Person struct and then marshals it into a nicely indented XML format. The use of struct tags like xml:">name" allows mapping struct fields to specific XML element names.
XML Deserialization
Deserialization is the process of converting an XML document into a Go data structure:
package main
import (
"encoding/xml"
"fmt"
)
func main() {
data := []byte(`<person>
<name>John Doe</name>
<age>30</age>
</person>`)
var p Person
err := xml.Unmarshal(data, &p)
if err != nil {
fmt.Printf("error: %v\n", err)
return
}
fmt.Printf("Person: %+v\n", p)
}
// Person struct for XML mapping
type Person struct {
XMLName xml.Name `xml:"person"`
Name string `xml:"name"`
Age int `xml:"age"`
}
Here, xml.Unmarshal is used to deserialize the XML data into a Person struct. It's crucial to have the struct tags correctly set up to ensure appropriate field mapping.
Using Attributes in XML
Sometimes, data in XML is stored as attributes rather than elements. You can use struct tags to handle both elements and attributes:
package main
import (
"encoding/xml"
"fmt"
)
type Plant struct {
XMLName xml.Name `xml:"plant"`
ID int `xml:"id,attr"`
Name string `xml:"name"`
}
func main() {
plant := Plant{ID: 27, Name: "Sunflower"}
output, _ := xml.MarshalIndent(plant, "", " ")
fmt.Printf("%s\n", output)
}
In this code, an attribute is denoted with an ,attr suffix in the struct tag for the ID field. During XML serialization, it appears as an attribute in the resulting XML.
Conclusion
The `encoding/xml` package in Go provides essential functionality for dealing with XML data. Understanding how to serialize and deserialize XML documents and using struct tags for proper mappings will significantly ease XML processing tasks. With these foundational concepts and examples, you can effectively manage XML in your Go applications.