不要打印XML输出,而是创建XML文件。

huangapple go评论83阅读模式
英文:

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(&quot;&lt;card&gt;\n&quot;)
    fmt.Printf(&quot;&lt;title&gt;&quot;%s&quot;&lt;/title&gt;\n&quot;, properties[&quot;/type/object/name&quot;])
    fmt.Printf(&quot;https://usercontent.googleapis.com/freebase/v1/image&quot;%s&quot;\n&quot;, id)
    fmt.Printf(&quot;&lt;text&gt;%s&lt;/text&gt;\n&quot;, properties[&quot;/common/document/text&quot;])
    fmt.Println(&quot;&lt;facts&gt;&quot;)
    for k, v := range properties {
	    for _,value := range v {
    	    fmt.Printf(&quot;&lt;fact property=\&quot;%s\&quot;&gt;%s&lt;/fact&gt;\n&quot;, k, value)
	    }
    }
    fmt.Println(&quot;&lt;/facts&gt;&quot;)
    fmt.Println(&quot;&lt;/card&gt;&quot;)

答案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(&quot;file.extension&quot;)

file being the variable the file is assigned to.

Then one can continually write to the file using:

fmt.Fprintf(file, &quot;text in file&quot;)

huangapple
  • 本文由 发表于 2014年4月2日 20:36:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/22811717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定