Print new line in xml file when \n literally prints \n

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

Print new line in xml file when \n literally prints \n

问题

我正在尝试在Golang中编写一个.xml文件,当我尝试写入一个新行并使用\n时,它会将\n作为字符串的一部分直接打印出来。

我该如何强制在文件中打印一个新行?

以下是我目前的代码:

fmt.Fprint(file, "<card>\n")
fmt.Fprintf(file, `<title>title</title>\n`)

但实际打印出来的是<card>\n<title>title</title>\n

英文:

I'm trying to write a .xml file in golang and when I try to write to a newline and use \n, it literally prints \n as part of the string.

How can I force a new line to be printed in the file?

Here is what my code looks like so far:

fmt.Fprint(file, &quot;&lt;card&gt;\n&quot;)
fmt.Fprintf(file, `&lt;title&gt;title&lt;/title&gt;\n`)

and that is printing &lt;card&gt;\n&lt;title&gt;title&lt;/title&gt;\n

答案1

得分: 2

实际上,它正在打印

<card>
<title>title</title>\n

你可以在这里看到。

原因是反斜杠在原始字符串中不会被插值,即用`括起来的字符串。如果你将第二行替换为

fmt.Fprintf("<title>title</title>\n")

你的程序应该按预期工作。

英文:

Actually, it's printing

&lt;card&gt;
&lt;title&gt;title&lt;/title&gt;\n

As you can see here.

The reason is that backslashes are not interpolated in raw strings, i.e. strings that are enclosed with `. If you replace your second line with

fmt.Fprintf(&quot;&lt;title&gt;title&lt;/title&gt;\n&quot;)

your program should work as intended.

huangapple
  • 本文由 发表于 2014年10月15日 03:49:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/26369145.html
匿名

发表评论

匿名网友

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

确定