Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Encoding and Data Formats

The Go encoding/xml package

Overview of Go's encoding/xml package: Marshal, Unmarshal, struct tags for elements, attributes, chardata and nested paths, Decoder tokens and common pitfalls.

encoding/xml maps Go structs to XML documents and back, in the same spirit as encoding/json. xml.Marshal produces XML bytes, xml.Unmarshal fills a struct, and xml.NewDecoder / xml.NewEncoder handle streams and token-by-token processing.

Struct tags describe the shape: which fields are attributes, which are child elements, which hold the text of an element, and where nested paths such as a>b>c sit. The special field XMLName names the element itself.

Go
type Item struct {
    XMLName xml.Name `xml:"item"`
    ID      int      `xml:"id,attr"`
    Name    string   `xml:"name"`
}

Try it

Go Marshal with attributes and nesting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Unmarshal and stream tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func Marshal(v any) ([]byte, error)
func MarshalIndent(v any, prefix, indent string) ([]byte, error)
func Unmarshal(data []byte, v any) error
func NewEncoder(w io.Writer) *Encoder
func NewDecoder(r io.Reader) *Decoder
func EscapeText(w io.Writer, s []byte) error

const Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n"
Tag Meaning
xml:"name" Child element called name.
xml:"name,attr" Attribute of the enclosing element.
xml:",chardata" Text content of the element.
xml:",cdata" Written as <![CDATA[...]]>.
xml:",innerxml" Raw XML inside the element, copied verbatim.
xml:",comment" Written as an XML comment (encoding only).
xml:",any" On decoding, catches children not matched by any other field.
xml:"a>b>c" Nest the value under elements a and b.
xml:",omitempty" Skip empty values.
xml:"-" Ignore the field.
XMLName xml.Name Names the element; with a tag it also checks the name on decoding.

Tokens. Decoder.Token returns StartElement, EndElement, CharData, Comment, ProcInst or Directive. Decoder.DecodeElement(&v, &start) decodes just one subtree, which is how you process huge files with constant memory.

Usage notes

  • Marshal does not add the XML declaration. Prepend xml.Header yourself.
  • Text is escaped (&amp;, &lt;, quotes), so values are safe; invalid XML characters cause an error.
  • Whitespace and chardata: a plain ,chardata field collects all text directly inside the element, including newlines between children.
  • Namespaces are limited. Names carry a Space and Local part; produce prefixes with the xmlns: attribute by hand. For namespace-heavy formats (SOAP, SVG toolchains) expect friction.
  • Strictness: the decoder is strict by default. Set dec.Strict = false and dec.AutoClose = xml.HTMLAutoClose to cope with sloppy markup, though it is not an HTML parser.
  • Non-UTF-8 input: the decoder returns an error for other charsets unless you set dec.CharsetReader.
  • Maps are not supported as struct fields in Marshal; use slices of structs.
  • Security: XML is an attack surface. Go's decoder does not expand external entities, but limit input size (billion-laughs style growth is bounded by your own data), and never trust names or paths.