如何动态更改xml节点?

I am using golang to change the xml node dynamically? some struct is as the following:

type Row struct {
XMLName xml.Name `xml:"row"`
R string `xml:"r,attr,omitempty"`
}

after xml.Marshal(), it output maybe "<row r="123"></row>" but i want to change the "<row></row>" to "<myrow></myrow>" if some condition is true.

how to dynamically change the xml node using golang?

Here's a working example: Playground

xml.Name has a field Local that contains the name for the tag.

If you set the value of Local to "myrow" it will output the struct as <myrow r="..."></myrow>.

Also, you have to remove the xml tag from the XMLName field. When the xml packages sees this tag (xml:"row") it will automatically name the tag "row", no matter what XMLName contains.

If you remove the annotation on the XMLName field of the struct, then you can change its value to adjust how the struct will be marshalled. For instance:

r.XMLName = xml.Name{"", "myrow"}

Would set the element name to myrow with an empty namespace. The annotation needs to be removed because it will take precedence over the value of XMLName.

You can see the results of this here: http://play.golang.org/p/3hGbE5WO8D