gpt4 book ai didi

xml - 在 Go 中将 XML 代码写入 XML 文件

转载 作者:IT王子 更新时间:2023-10-29 00:33:37 26 4
gpt4 key购买 nike

我有一个打印行 XML 代码的脚本,但我需要它来编写一个新的 XML 文件,然后将 XML 代码写入该文件而不是打印它。

这是打印 XML 代码的函数

func processTopic(id string, properties map[string][]string) {
fmt.Printf("<card entity=\"%s\">\n", id)
fmt.Println(" <facts>")
for k, v := range properties {
for _,value := range v {
fmt.Printf(" <fact property=\"%s\">%s</fact>\n", k, value)
}
}
fmt.Println(" </facts>")
fmt.Println("</card>")
}

我怎样才能让它写入 XML 文件,然后将代码写入该 XML 文件?

最佳答案

虽然打印 XML 可能没问题,但为什么不使用 encoding/xml 包呢?准备好您的 XML 结构:

type Card struct {
Entity string `xml:"entity,attr"`
Facts Facts
}

type Facts struct {
Fact []Fact
}

type Fact struct {
Property string `xml:"property,attr"`
Value string `xml:",innerxml"`
}

像这样创建你的数据结构(running example on play):

card := &Card{
Entity: "1234id",
Facts: Facts{[]Fact{
Fact{Property: "prop1", Value: "val1"},
Fact{Property: "prop2", Value: "val2"},
}},
}

现在您可以将结构编码为 XML 并将其直接写入 io.Writer:

writer, err := os.Open("/tmp/tmp.xml")

encoder := xml.NewEncoder(writer)
err := encoder.Encode(data)

if err != nil { panic(err) }

关于xml - 在 Go 中将 XML 代码写入 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19238114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com