douju7245
2015-01-21 10:18
浏览 145

如何动态更改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?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douqian9729 2015-01-21 11:33
    已采纳

    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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongya4335 2015-01-21 11:35

    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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题