英文:
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:"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?
答案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 "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.
答案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{"", "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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论