我有一个打印行代码的脚本,但我需要它来编写一个新的
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>") }
解决方法
添加到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,value := range v { fmt.Fprintf(w," <fact property=\"%s\">%s</fact>\n",value) } } fmt.Fprintln(w," </facts>") fmt.Fprintln(w,"</card>") }
打印到屏幕(标准输出):
processTopic(os.Stdout,id,properties)
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,properties)