encoding/xml

encoding/xml Unmarshal, Marshal, and MarshalIndent, including SyntaxError, and why the output is not a semantic canonical form or a promise of safety for untrusted XML, checked on Go 1.24.0.

模块页正文目前为英文。

The encoding/xml package implements a simple XML 1.0 parser that understands XML namespaces, plus helpers to marshal Go values. Official documentation also records an inherent limitation: XML elements are order-dependent collections of anonymous values, while a Go struct is an order-independent collection of named fields, so the mapping is imperfect. This page does not rewrite encoding/json.

Marshal and Unmarshal are not a semantic canonicalization. Extra whitespace, attribute spacing, comments, and similar spellings in the input can disappear or be rewritten. Two documents that a reader might call equivalent can therefore produce different bytes, and the marshaled form need not match the original text.

The official package documentation does not present encoding/xml as a complete defense against untrusted XML. This page does not invent a vulnerability, does not construct a hostile document, and does not promise that the parser is safe for unauthenticated input. Examples parse fixed strings in memory and do not open network URLs or private files.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
xml.Unmarshal, xml.Marshal, xml.MarshalIndentUnmarshal fills a tagged struct. Marshal and MarshalIndent emit XML that need not match the original spelling. A truncated document returns *xml.SyntaxError.

Unmarshal, Marshal, and syntax errors

Unmarshal decodes XML into a value, typically a struct with field tags such as `xml:"id,attr"` and `xml:",chardata"`. Marshal writes a Go value as XML. MarshalIndent adds a prefix and indent string for readability; that is formatting, not a canonical form of the original document.

Ill-formed input returns an error. A truncated document in this example returns a *xml.SyntaxError. The program never writes the output as a fetched document, and it does not include a DTD or entity payload.

xml.Unmarshal, xml.Marshal, xml.MarshalIndent

func Unmarshal(data []byte, v any) error
func Marshal(v any) ([]byte, error)
func MarshalIndent(v any, prefix, indent string) ([]byte, error)
type SyntaxError struct {
	Msg  string
	Line int
}

Unmarshal fills a tagged struct. Marshal and MarshalIndent emit XML that need not match the original spelling. A truncated document returns *xml.SyntaxError.

ParameterDescription
data, vUnmarshal reads data into v. v should be a pointer to the destination value.
v (Marshal)The value to encode. Channels, functions, and maps cannot be marshaled and return an error.
prefix, indentMarshalIndent writes prefix at the start of each indented line and indent at each nesting level. This changes whitespace only in the output; it does not recover comments dropped during Unmarshal.

Returns: Unmarshal returns nil on success. Marshal and MarshalIndent return the encoded bytes and an error. This example prints the SyntaxError with its type and message.

Errors

  • *xml.SyntaxError — Returned when the input is not well-formed XML. The truncated <box> document in this example reports unexpected EOF on line 1.
  • The input has extra spaces and a comment. After Unmarshal, Marshal and MarshalIndent both omit the comment and the extra spaces. That is why this is not a semantic canonical form of the original bytes.
go
package main

import (
	"encoding/xml"
	"fmt"
)

type Item struct {
	ID   string `xml:"id,attr"`
	Body string `xml:",chardata"`
}

type Box struct {
	XMLName xml.Name `xml:"box"`
	Items   []Item   `xml:"item"`
}

func main() {
	in := []byte(`<box  ><item  id="a"><!--note-->one</item><item id="b">two</item></box>`)
	var box Box
	if err := xml.Unmarshal(in, &box); err != nil {
		fmt.Println("unmarshal", err)
		return
	}
	out, err := xml.Marshal(box)
	fmt.Printf("%s %s %v\n", box.Items[0].ID, box.Items[0].Body, err)
	fmt.Printf("%s\n", in)
	fmt.Printf("%s\n", out)
	indented, err := xml.MarshalIndent(box, "", "  ")
	fmt.Printf("%v\n%s\n", err, indented)
	err = xml.Unmarshal([]byte(`<box>`), new(Box))
	fmt.Printf("%T %v\n", err, err)
}

Expected output

a one <nil>
<box  ><item  id="a"><!--note-->one</item><item id="b">two</item></box>
<box><item id="a">one</item><item id="b">two</item></box>
<nil>
<box>
  <item id="a">one</item>
  <item id="b">two</item>
</box>
*xml.SyntaxError XML syntax error on line 1: unexpected EOF

Related: XML Diff tool, XML formatter, encoding/json, Official encoding/xml

Official documentation →