Skip to main content
Go offers built-in support for XML and XML-like formats with the encoding/xml package.

Defining XML Structures

Use struct tags to control XML encoding and decoding:
type Plant struct {
    XMLName xml.Name `xml:"plant"`
    Id      int      `xml:"id,attr"`
    Name    string   `xml:"name"`
    Origin  []string `xml:"origin"`
}

func (p Plant) String() string {
    return fmt.Sprintf("Plant id=%v, name=%v, origin=%v",
        p.Id, p.Name, p.Origin)
}
The XMLName field dictates the name of the XML element. The id,attr tag makes Id an XML attribute rather than a nested element.

Encoding to XML

Use MarshalIndent to produce human-readable output:
coffee := &Plant{Id: 27, Name: "Coffee"}
coffee.Origin = []string{"Ethiopia", "Brazil"}

out, _ := xml.MarshalIndent(coffee, " ", "  ")
fmt.Println(string(out))
Output:
<plant id="27">
  <name>Coffee</name>
  <origin>Ethiopia</origin>
  <origin>Brazil</origin>
</plant>

Adding XML Header

Append the XML header explicitly:
fmt.Println(xml.Header + string(out))
Output:
<?xml version="1.0" encoding="UTF-8"?>
<plant id="27">
  <name>Coffee</name>
  <origin>Ethiopia</origin>
  <origin>Brazil</origin>
</plant>

Decoding from XML

Parse XML bytes into a data structure:
var p Plant
if err := xml.Unmarshal(out, &p); err != nil {
    panic(err)
}
fmt.Println(p)
// Output: Plant id=27, name=Coffee, origin=[Ethiopia Brazil]
If the XML is malformed or cannot be mapped onto the struct, a descriptive error will be returned.

Nested XML Elements

Use the parent>child>element tag to nest elements:
tomato := &Plant{Id: 81, Name: "Tomato"}
tomato.Origin = []string{"Mexico", "California"}

type Nesting struct {
    XMLName xml.Name `xml:"nesting"`
    Plants  []*Plant `xml:"parent>child>plant"`
}

nesting := &Nesting{}
nesting.Plants = []*Plant{coffee, tomato}

out, _ = xml.MarshalIndent(nesting, " ", "  ")
fmt.Println(string(out))
Output:
<nesting>
  <parent>
    <child>
      <plant id="27">
        <name>Coffee</name>
        <origin>Ethiopia</origin>
        <origin>Brazil</origin>
      </plant>
      <plant id="81">
        <name>Tomato</name>
        <origin>Mexico</origin>
        <origin>California</origin>
      </plant>
    </child>
  </parent>
</nesting>

XML Struct Tags

Sets the XML element or attribute name
Encodes the field as an XML attribute
Encodes the field as character data, not an element
Creates nested XML elements
Verbatim XML content

Key Functions

Marshal
func(v any) ([]byte, error)
Encodes a value to XML bytes
MarshalIndent
func(v any, prefix, indent string) ([]byte, error)
Encodes a value to XML bytes with indentation
Unmarshal
func(data []byte, v any) error
Decodes XML bytes into a value

Package Reference

Build docs developers (and LLMs) love