Dynamically Defining XML Element Names in Go
Consider an XML file with two elements of identical structure, except for the element names. To represent these elements in Go, a struct with a dynamic element name is desired.
type Person struct { XMLName string `xml:"???` // How to make this dynamic? E1 string `xml:"ELEM1"` E2 string `xml:"ELEM2"` E3 string `xml:"ELEM3"` E4 string `xml:"ELEM4"` }
The xml.Name type is introduced here. Its Local field allows for the dynamic setting of element names:
type Person struct { XMLName xml.Name E1 string `xml:"ELEM1"` // ... }
At runtime, the element name can be assigned:
person := Person{ XMLName: xml.Name{Local: "Person"}, // ... }
Note that the struct fields (E1 - E4) must be exported (start with uppercase letters) to be included in the XML output.
For a practical example, refer to the following playground:
http://play.golang.org/p/bzSutFF9Bo
The above is the detailed content of How to Dynamically Set XML Element Names in Go Structs?. For more information, please follow other related articles on the PHP Chinese website!