How to customize XML element and attribute names during encoding and decoding in Go?

In Go, XML element and attribute names can be customized during encoding and decoding using struct tags. Struct tags can be used to define the XML field name and attribute name.

Here's an example:

  1. Define a struct type with XML field and attribute names using struct tags:
type Person struct { XMLName xml.Name `xml:"person"` Name string `xml:"name"` Age int `xml:"age"` Country string `xml:"country,attr"` }
  1. Encode the struct into XML using the customized names:
p := Person{ Name: "John", Age: 35, Country: "USA", } xmlData, err := xml.Marshal(p) if err != nil { fmt.Println("Error marshaling XML:", err) return } fmt.Println(string(xmlData))
  1. Decode the XML into the struct with customized names:
xmlData := []byte(` <person> <name>John</name> <age>35</age> <country>USA</country> </person> `) var p Person err := xml.Unmarshal(xmlData, &p) if err != nil { fmt.Println("Error unmarshaling XML:", err) return } fmt.Println(p)

In the above example, the XML field names are customized using the xml struct tag. The XMLName field has the xml:"person" tag, specifying the XML element name as "person". The Name field has the xml:"name" tag, specifying the XML element name as "name". The Country field has the xml:"country,attr" tag, specifying the XML attribute name as "country".

When encoding the struct to XML, the xml.Marshal function will use the custom names specified in the struct tags. Similarly, when decoding XML into the struct, the xml.Unmarshal function will map the XML elements and attributes to the struct fields based on the struct tags.