The task of constructing XML documents from Go structures can pose challenges, especially when dealing with varying element names. The question arises: can we define a Go struct that allows for dynamic element names during the XML marshaling process?
The Go documentation states that the XMLName field in a struct must be of type xml.Name, not a string. This struct contains two fields: "Space" and "Local." To set a dynamic element name, modify the "Local" field within the xml.Name type.
type Person struct { XMLName xml.Name E1 string `xml:"ELEM1"` // ... }
In this example, we'll have a struct with the element name being "Person" or "Sender" based on the value stored in the XMLName.Local field.
import ( "encoding/xml" "fmt" ) type Person struct { XMLName xml.Name E1 string `xml:"ELEM1"` // ... } func main() { person := Person{XMLName: xml.Name{Local: "Person"}, E1: "Value1"} sender := Person{XMLName: xml.Name{Local: "Sender"}, E1: "Value1"} // Marshal the struct into XML personXML, _ := xml.Marshal(person) senderXML, _ := xml.Marshal(sender) fmt.Println(string(personXML)) fmt.Println(string(senderXML)) }
This example produces two distinct XML documents, one with the element name "Person" and the other with the element name "Sender."
For an interactive version of this example, visit the Go Playground: http://play.golang.org/p/bzSutFF9Bo
The above is the detailed content of How Can I Marshal XML Elements with Dynamic Names in Go?. For more information, please follow other related articles on the PHP Chinese website!