Go by Example

XML

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

The encoding/xml package maps Go structs to XML elements and attributes. Struct tags name XML fields; the attr option marks 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 holds the document in memory; use xml.Decoder for large inputs. Unknown elements are ignored, so validate partner documents when the schema matters. Namespace-heavy formats may need explicit namespace handling. Test generated output against the receiving system's schema.

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