Skip to content

XML

The encoding/xml package provides XML marshaling and unmarshaling similar to JSON. Struct tags specify element names and attributes.

Marshal a struct to XML.

package main
import (
"encoding/xml"
"fmt"
)
type Person struct {
XMLName xml.Name `xml:"person"`
Name string `xml:"name"`
Age int `xml:"age"`
}
func main() {
p := Person{Name: "Alice", Age: 30}
data, _ := xml.MarshalIndent(p, "", " ")
fmt.Println(string(data))
}
Terminal window
<person>
<name>Alice</name>
<age>30</age>
</person>