The name of the root tag can be changed using the XMLName field in a data structure. There are some other features of field tags that can be really useful:
- Tags with - are omitted.
- A tag with the attr option becomes an attribute of the parent element.
- A tag with the innerxml option is written verbatim, useful for lazy decoding.
- The omitempty option works the same as it does for JSON; it will not produce a tag for zero values.
- The tag can contain a path in the XML using > as a separator, as a > b > c.
- Anonymous struct fields are treated as if the fields of its value were in the outer struct.
Let's take a look at a practical example that uses some of these features:
type Character struct {
XMLName struct{} `xml:"character"`
Name string `xml:"name"`
Surname string `xml:"surname"`
Job string `xml:"details>job,omitempty"`
YearOfBirth int `xml:"year_of_birth,attr,omitempty"`
IgnoreMe string `xml:"-"`
}
This structure produces the following XML:
<character year_of_birth="1871">
<name>Henry</name>
<surname>Wentworth Akeley</surname>
<details>
<job>farmer</job>
</details>
</character>
The full example is available here: https://play.golang.org/p/6zdl9__M0zF.