Go Encoding Xml
The encoding/xml package is used for parsing XML-formatted data into a struct.
Example
Struct Tags
Unmarshal maps an XML element to a struct using the tags of struct fields and the following hierarchy of rules:
If the struct has tag ",innerxml" and type []byte or string, Unmarshal accumulates the raw XML nested inside that element in that field. The rest of the rules still apply.
If the struct has a field named XMLName of type xml.Name, Unmarshal stores that element's name in that field.
If the XMLName field has an associated tag of the form "name" or "namespace-URL name", that element must have the given name (and name space) or Unmarshal will return an error.
If an attribute matches a field with an associated tag containing ",attr", Unmarshal maps that attribute to that field.
If an attribute did not match the previous rule and there is a field with tag ",any,attr", Unmarshal maps that attribute to the first such field.
Character data accumulates in the first field that has tag ",chardata" and type []byte or string.
- If there is no such field, character data is discarded.
Comments accumulate in the first field that has tag ",comment" and type []byte or string.
- If there is no such field, comments are discarded.
If a sub-element matches the prefix of a tag formatted as "a" or "a>b>c", Unmarshal descends into the XML structure looking for sub-elements with the given names, and will map the innermost elements to that field.
">a" is equivalent to "a"
If a sub-element matches a field's XMLName tag and the field has no explicit name tag, Unmarshal maps that sub-element to struct field.
If a sub-element matches a field without any mode flags (",attr", ",chardata", etc), Unmarshal maps that sub-element to that field.
If a sub-element hasn't matched any of the above rules and there is a field with tag ",any", Unmarshal maps that sub-element to that field.
- An anonymous field is handled as if the fields of its value were part of the outer struct.
A field with tag "-" is never used.
Element Fields
Names for fields can be set by any of:
- matching the name of the struct field to the XML element name
using an XML tag like xml:"name"
using a XMLName field of type xml.Name with the above pattern
As an example:
type Html struct { head Head Body Body `xml:"body"` XMLName xml.Name `xml:"html"` }
Note that this is purely a demonstration; fields need to be public, so head should be capitalized.
Attribute fields
Names for attributes can be set by any of:
matching the name of the struct field to the attribu8te name with the ",attr" tag
using an XML tag like xml:"name,attr"