Dynamic Element Names in XML Marshaling
XML documents often contain elements with similar structures but different names. To handle this in Go, you may wonder if it's possible to modify the element name dynamically during XML marshaling.
Struct Definition
Let's consider the following XML document with two elements, "PERSON" and "SENDER," containing the same elements with different names:
<PERSON> <ELEM1>...</ELEM1> <ELEM2>...</ELEM2> <ELEM3>...</ELEM3> <ELEM4>...</ELEM4> </PERSON> <SENDER> <ELEM1>...</ELEM1> <ELEM2>...</ELEM2> <ELEM3>...</ELEM3> <ELEM4>...</ELEM4> </SENDER>
Initially, you might try to define a struct like this, where the element name is statically set:
type Person struct { XMLName string `xml:"PERSON"` // Static element name E1 string `xml:"ELEM1"` E2 string `xml:"ELEM2"` E3 string `xml:"ELEM3"` E4 string `xml:"ELEM4"` }
Dynamic Element Name
To make the element name dynamic, you need to use the xml.Name type instead of a string:
type Person struct { XMLName xml.Name E1 string `xml:"ELEM1"` E2 string `xml:"ELEM2"` E3 string `xml:"ELEM3"` E4 string `xml:"ELEM4"` }
Now, you can set the element name dynamically using the Local field of xml.Name:
person := Person{ XMLName: xml.Name{Local: "Person"}, // ... Set other fields }
This allows you to dynamically generate the XML element name based on the specific data you're marshaling.
Example
A working example can be found on the Go Playground: http://play.golang.org/p/bzSutFF9Bo.
With this technique, you can create structs that handle XML elements with varying names, providing flexibility and extensibility in your XML handling code.
The above is the detailed content of How Can I Dynamically Set XML Element Names During Marshaling in Go?. For more information, please follow other related articles on the PHP Chinese website!