Go by Example

XML

Use encoding/xml tags for elements and attributes, marshal or unmarshal values, and use Decoder for large inputs.

XML is a text format that marks data with named elements and attributes. The encoding/xml package converts between XML and Go structs. Struct tags tell Go the element name for a field; the attr option makes it an attribute.

Marshal a value to XML, then decode it with xml.Unmarshal. Unknown elements are ignored unless you add your own validation.

package main
 
import (
    "encoding/xml"
    "fmt"
)
 
type Book struct {
    XMLName xml.Name `xml:"book"`
    ID      int      `xml:"id,attr"`
    Title   string   `xml:"title"`
}
 
func main() {
    data, err := xml.Marshal(Book{Title: "Go"})
    if err != nil {
        panic(err)
    }
    fmt.Println(xml.Header + string(data))
 
    var book Book
    if err := xml.Unmarshal(data, &book); err != nil {
        panic(err)
    }
    fmt.Println(book.Title)
}

In production

xml.Unmarshal reads the whole document into memory. Use xml.Decoder for a large input so it can be read piece by piece. Unknown elements are ignored, so check the input when your program requires certain fields. If another system requires a specific XML structure, test your output against its documented format.

Enjoyed this? Get more software craft delivered to your inbox.