encoding/xml

Guided tour · Encoding · pkg.go.dev →

XML encode/decode via reflection and struct tags. Same model as encoding/json.

Marshal and Unmarshal

Struct tags control element/attr mapping

type Book struct {
    XMLName xml.Name `xml:"book"`
    Title   string   `xml:"title"`
    Pages   int      `xml:"pages,attr"`
}

b, _ := xml.MarshalIndent(Book{Title: "Go", Pages: 300}, "", "  ")
fmt.Println(string(b))
Output
<book pages="300">
  <title>Go</title>
</book>

chardata, innerxml, omitempty

type P struct {
    XMLName xml.Name `xml:"p"`
    Text    string   `xml:",chardata"`
}

Streaming with Decoder

Token loop — walk element-by-element

Use for huge XML that doesn't fit in memory.

dec := xml.NewDecoder(r)
for {
    tok, err := dec.Token()
    if err == io.EOF { break }
    switch t := tok.(type) {
    case xml.StartElement:
        if t.Name.Local == "item" {
            var it Item
            dec.DecodeElement(&it, &t)
        }
    }
}