skip to content
Alvin Lucillo

Customize XML tags

/ 1 min read

In the example below, when the slice of users is marshalled into XML data, the first and last name values are combined into a single fullname tag. This is possible by implementing the MarshalXML function that the package will recognize.

package main

import (
	"encoding/xml"
	"fmt"
)

type User struct {
	FirstName string
	LastName  string
	Age       int
}

func (u User) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
	start.Name.Local = "user"
	if err := e.EncodeToken(start); err != nil {
		return err
	}

	if err := e.EncodeElement(fmt.Sprintf("%s %s", u.FirstName, u.LastName), xml.StartElement{Name: xml.Name{Local: "fullname"}}); err != nil {
		return err
	}
	if err := e.EncodeElement(u.Age, xml.StartElement{Name: xml.Name{Local: "age"}}); err != nil {
		return err
	}

	return e.EncodeToken(start.End())
}

func main() {

	users := []User{{FirstName: "Marie", LastName: "Laurent", Age: 49}, {FirstName: "Joao", LastName: "Carvalho", Age: 98}}
	data, err := xml.Marshal(users)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s", data)

}

Output:

<user><fullname>Marie Laurent</fullname><age>49</age></user><user><fullname>Joao Carvalho</fullname><age>98</age></user>