XML

suggest change

Package encoding/xml in standard library provides functionality for serializing data as XML and parsing XML.

Parse XML into a struct

Parsing XML is similar to parsing JSON. You define structs that map to the XML and unmarshal from a []byte or an io.Reader into a struct.

var xmlStr = `
<people>
	<person age="34">
		<first-name>John</first-name>
		<address>
			<city>San Francisco</city>
			<state>CA</state>
		</address>
	</person>

	<person age="23">
		<first-name>Julia</first-name>
	</person>
</people>`

type People struct {
	Person []Person `xml:"person"`
}

type Person struct {
	Age       int     `xml:"age,attr"`
	FirstName string  `xml:"first-name"`
	Address   Address `xml:"address"`
}

type Address struct {
	City  *string `xml:"city"`
	State string  `xml:"state"`
}

	var people People
	data := []byte(xmlStr)
	err := xml.Unmarshal(data, &people)
	if err != nil {
		log.Fatalf("xml.Unmarshal failed with '%s'\n", err)
	}
	fmt.Printf("%#v\n\n", people)
main.People{Person:[]main.Person{main.Person{Age:34, FirstName:"John", Address:main.Address{City:(*string)(0xc00005a400), State:"CA"}}, main.Person{Age:23, FirstName:"Julia", Address:main.Address{City:(*string)(nil), State:""}}}}

Unlike xml.Marshal, xml.Unmarshal requires a pointer. If the argument is not a pointer, it returns an error and leaves the value unchanged.

In XML a value can be an element (<state>CA</state>) or an attribute (<person age="34">).

In xml struct tags, the element form is the default. To use an attribute, add ,attr, as done for Age.

All struct fields are optional. When an element is absent, the field is left unchanged. Decoding into a newly initialized struct therefore leaves absent fields at the zero value for their type.

Field City shows that XML decoder can automatically decode into a pointer to a value.

This is useful when you need to know if a value was present in XML or not. If we used string for City field, we wouldn’t know if empty string means:

By using a pointer to a string we know that nil means there was no value.

Serialize a struct as XML

type People struct {
	XMLName        xml.Name `xml:"people"`
	Person         []Person `xml:"person"`
	noteSerialized int
}

type Person struct {
	Age       int     `xml:"age,attr"`
	FirstName string  `xml:"first-name"`
	Address   Address `xml:"address"`
}

type Address struct {
	City  string `xml:"city"`
	State string `xml:"state"`
}

	people := People{
		Person: []Person{
			Person{
				Age:       34,
				FirstName: "John",
				Address:   Address{City: "San Francisco", State: "CA"},
			},
		},
		noteSerialized: 8,
	}
	d, err := xml.Marshal(&people)
	if err != nil {
		log.Fatalf("xml.Marshal failed with '%s'\n", err)
	}
	fmt.Printf("Compact XML: %s\n\n", string(d))

	d, err = xml.MarshalIndent(&people, "", "  ")
	if err != nil {
		log.Fatalf("xml.MarshalIndent failed with '%s'\n", err)
	}
	fmt.Printf("Pretty printed XML:\n%s\n", string(d))
Compact XML: <people><person age="34"><first-name>John</first-name><address><city>San Francisco</city><state>CA</state></address></person></people>

Pretty printed XML:
<people>
  <person age="34">
    <first-name>John</first-name>
    <address>
      <city>San Francisco</city>
      <state>CA</state>
    </address>
  </person>
</people>

Both xml.Marshal and xml.MarshalIndent take interface{} as the first argument. We can pass any Go value, and it is wrapped in an interface{} with its dynamic type.

Marshaller will use reflection to inspect passed value and encode it as XML strings.

When serializing structs, only exported fields (names that start with a capital letter) are serialized and deserialized.

In our example, noteSerialized is not serialized.

Structs are serialized as XML elements.

Simple types can be serialized as XML elements or attributes (the Age field in Person).

By default, the element or attribute name is the field name.

We can provide custom mappings with struct tags.

xml:"city" tells XML encoder to use name city for field City.

When serializing structs, passing the value or a pointer to xml.Marshal generates the same result.

Passing a pointer is more efficient because passing by value creates unnecessary copy.

xml.MarshalIndent pretty-prints nested elements. The result takes more space but is easier to read.

XMLName controls the name of the top-level element. Without it, the encoder would derive the element name from the struct type:

<People>
    ....
</People>

Pull (streaming) XML parsing

Hybrid XML parsing: combine pull and unmarshal

Parse XML from file

Configuring XML parsing and serialization

Custom XML marshaling

Easy generation of XML struct definition

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents