将XML代码写入Go中的XML文件

gom*_*ngo 4 xml go

我有一个打印行代码的脚本,但我需要它来编写一个新的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>")
}
Run Code Online (Sandbox Code Playgroud)

如何让它编写XML文件,然后将代码写入该XML文件?

nem*_*emo 15

打印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"`
}
Run Code Online (Sandbox Code Playgroud)

像这样创建你的数据结构(在播放时运行示例):

card := &Card{
    Entity: "1234id",
    Facts: Facts{[]Fact{
        Fact{Property: "prop1", Value: "val1"},
        Fact{Property: "prop2", Value: "val2"},
    }},
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

if err != nil { panic(err) }
Run Code Online (Sandbox Code Playgroud)


ANi*_*sus 3

添加到 bgp 的 (+1) 正确答案;通过更改函数以采用 io.Writer 作为参数,您可以将 XML 输出到实现io.Writer接口的任何类型的输出。

func processTopic(w io.Writer, id string, properties map[string][]string) {
    fmt.Fprintf(w, "<card entity=\"%s\">\n", id)
    fmt.Fprintln(w, "  <facts>")
    for k, v := range properties {
        for _,value := range v {
            fmt.Fprintf(w, "    <fact property=\"%s\">%s</fact>\n", k, value)
        }
    }
    fmt.Fprintln(w, "  </facts>")
    fmt.Fprintln(w, "</card>")
}
Run Code Online (Sandbox Code Playgroud)

打印到屏幕(标准输出):

processTopic(os.Stdout, id, properties)
Run Code Online (Sandbox Code Playgroud)

写入文件(代码取自bgp的答案):

f, err := os.Create("out.xml") // create/truncate the file
if err != nil { panic(err) } // panic if error
defer f.Close() // make sure it gets closed after
processTopic(f, id, properties)
Run Code Online (Sandbox Code Playgroud)