doushi7761 2013-10-08 02:30
浏览 57
已采纳

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

I have a script that print-lines XML code, but I need it to write a new XML file and then write the XML code to the file instead of printing it.

Here is the function that prints the XML code

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

How can I get it to write an XML file and then write the code to that XML file?

  • 写回答

4条回答 默认 最新

  • dongwei8729 2013-10-08 08:50
    关注

    To add to bgp's (+1) correct answer; by changing the function to take a io.Writer as argument, you can output your XML to any type of output implementing the io.Writer interface.

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

    Printing to screen (Stdout):

    processTopic(os.Stdout, id, properties)
    

    Writing to file (code taken from bgp's answer):

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab