is there a way to marshal XML in the following example such that the sub-elements under MyElement
are marshaled under the root MyXML
as follows:
type MyXML struct {
XMLName xml.Name `xml:"myXML"`
Element *MyElement `xml:",any"`
}
type MyElement struct {
A string `xml:"a"`
B string `xml:"b"`
C string `xml:"c"`
}
I’d like the following result:
<myXML>
<a>blah</a>
<b>blah</b>
<c>blah</c>
</myXML>
If I marshal as is I get:
<myXML>
<Element>
<a>blah</a>
<b>blah</b>
<c>blah</c>
</Element>
</myXML>
Is this possible by way of implementing the xml.Marshaler interface via the MyElement struct?
Thanks!
You can make use of the XMLName
field of type xml.Name
on a struct to marshal it to the name you'd like.
type MyXML struct {
XMLName xml.Name `xml:"myXML"`
A string `xml:"a"`
B string `xml:"b"`
C string `xml:"c"`
}
func main() {
testXML := MyXML{
A: "test a",
B: "test b",
C: "test c",
}
xmlBytes, err := xml.Marshal(testXML)
if err != nil {
fmt.Printf("error parsing xml: %s", err)
return
}
fmt.Println(string(xmlBytes))
}