英文:
Instead of printing XML output, create XML file
问题
在这段Go / Golang代码中,我正在打印XML。但是,我想知道如何使用这个输出创建一个XML文件。
我想这样做的原因是XML输出非常庞大,如果要将输出从终端复制粘贴,需要花费很长时间来全部选中,所以最好将其写入一个XML文件中。
以下是代码:
fmt.Printf("<card>\n")
fmt.Printf("<title>%s</title>\n", properties["/type/object/name"])
fmt.Printf("https://usercontent.googleapis.com/freebase/v1/image%s\n", id)
fmt.Printf("<text>%s</text>\n", properties["/common/document/text"])
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文件中。
英文:
In this Go / Golang code, I am printing XML. But instead of doing that, how can I create an XML file with this output?
The reason I want to do this is that the XML output is quite large and instead of copying and pasting the output from the terminal, since it would take quite a long time to highlight it all, it would be best if it was written to an XML file.
Here is the code:
fmt.Printf("<card>\n")
fmt.Printf("<title>"%s"</title>\n", properties["/type/object/name"])
fmt.Printf("https://usercontent.googleapis.com/freebase/v1/image"%s"\n", id)
fmt.Printf("<text>%s</text>\n", properties["/common/document/text"])
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>")
答案1
得分: 1
如评论中所提到的,可以使用os.Create()
来创建一个文件,示例如下:
file, _ := os.Create("file.extension")
其中,file
是文件分配给的变量。
然后,可以使用以下方式不断向文件中写入内容:
fmt.Fprintf(file, "text in file")
英文:
As mentioned in the comments one can create a file using os.Create()
like so:
file, _:=os.Create("file.extension")
file being the variable the file is assigned to.
Then one can continually write to the file using:
fmt.Fprintf(file, "text in file")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论