如何动态更改 XML 节点?

huangapple go评论78阅读模式
英文:

How to dynamically change the xml node?

问题

你可以使用xml.Unmarshal函数将XML数据解析为结构体,然后根据条件修改结构体中的字段值,最后使用xml.Marshal函数将结构体转换回XML数据。

以下是一个示例代码:

package main

import (
	"encoding/xml"
	"fmt"
)

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

func main() {
	// 原始XML数据
	xmlData := []byte(`<row r="123"></row>`)

	// 解析XML数据到结构体
	var row Row
	err := xml.Unmarshal(xmlData, &row)
	if err != nil {
		fmt.Println("解析XML失败:", err)
		return
	}

	// 根据条件修改字段值
	if true {
		row.XMLName.Local = "myrow"
	}

	// 将结构体转换为XML数据
	output, err := xml.Marshal(row)
	if err != nil {
		fmt.Println("转换为XML失败:", err)
		return
	}

	fmt.Println(string(output))
}

在上面的示例中,我们首先使用xml.Unmarshal函数将XML数据解析为Row结构体。然后,根据条件修改XMLName.Local字段的值为"myrow"。最后,使用xml.Marshal函数将修改后的结构体转换回XML数据,并打印输出。

请根据你的实际需求修改条件判断和字段修改的逻辑。

英文:

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

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

after xml.Marshal(), it output maybe &quot;&lt;row r=&quot;123&quot;&gt;&lt;/row&gt;&quot;
but i want to change the &quot;&lt;row&gt;&lt;/row&gt;&quot; to &quot;&lt;myrow&gt;&lt;/myrow&gt;&quot; if some condition is true.

how to dynamically change the xml node using golang?

答案1

得分: 3

这是一个可工作的示例:Playground

xml.Name有一个字段Local,其中包含标签的名称。

如果将Local的值设置为"myrow",它将输出结构体为<myrow r="..."></myrow>

此外,您必须从XMLName字段中删除xml标签。当xml包看到这个标签(xml:"row")时,它将自动将标签命名为"row",而不管XMLName包含什么。

英文:

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 &quot;myrow&quot; it will output the struct as &lt;myrow r=&quot;...&quot;&gt;&lt;/myrow&gt;.

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

答案2

得分: 1

如果你移除结构体的XMLName字段上的注释,那么你可以更改它的值以调整结构体的编组方式。例如:

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

将元素名称设置为myrow,并且命名空间为空。需要移除注释,因为它会优先于XMLName的值。

你可以在这里查看结果:http://play.golang.org/p/3hGbE5WO8D

英文:

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{&quot;&quot;, &quot;myrow&quot;}

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

huangapple
  • 本文由 发表于 2015年1月21日 18:18:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/28064641.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定