$Id: 189

Package [encoding/xml](<https://godoc.org/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 structures that map to the structure of XML and unmarshal from []byte slice or io.Reader into a struct.

https://codeeval.dev/gist/62992e0c515e5c5b663fe1ac96fd14bc

Unlike with serializing, when unmarshalling into a struct, we must pass a pointer to struct. Otherwise xml.Unmarshal will receive and modify a copy of the struct, not the struct itself. The copy will be then discarded after returning from xml.Unmarshal.

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

In xml struct tags element is the default. To switch to attribute, add ,attr to struct xml tag as done for Age.

All struct fields are optional. When not present in XML text their values will be untouched. When decoding into newly initialized struct their value will be zero value for a given 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

https://codeeval.dev/gist/abdf76b17b89f29219d43cf92a084dba

Both xml.Marshal and xml.MarshalIndent take [interface{}](<https://www.notion.so/kjkpublic/Empty-interface-c3315892508248fdb19b663bf8bff028>) as first argument. We can pass any Go value and it’ll be wrapped into interface{} with their type.

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

When serializing structs, only exported fields (whose names start with capital letter) are serialized / deserialized.