Go:在使用template.ParseFiles解析xml文件后,第一个“<”变成了“<”。

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

Go: After parse xml file with template.ParseFiles, the first "<" became "&lt;"

问题

我正在尝试使用template.ParseFiles()解析一个xml文件。

xml文件如下:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;in2&gt;
	&lt;unique&gt;{{.}}&lt;/unique&gt;
	&lt;moe&gt;100%&lt;/moe&gt;
&lt;/in2&gt;

但是在解析后,第一个&lt;变成了&amp;lt;,如下所示:

&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;in2&gt;
	&lt;unique&gt;something&lt;/unique&gt;
	&lt;moe&gt;100%&lt;/moe&gt;
&lt;/in2&gt;

我该如何正确解析xml文件?

这是我的代码:

func in2(w http.ResponseWriter, r *http.Request) {
	w.Header().Set(&quot;Content-Type&quot;, &quot;text/xml&quot;)
	t, err := template.ParseFiles(&quot;xml/in2.xml&quot;)
	if err != nil {
		fmt.Println(err)
		return
	}
	unique := &quot;something&quot;
	err = t.Execute(w, unique)
	if err != nil {
		fmt.Println(err)
	}
}
英文:

I am trying to parse a xml file using template.ParseFiles().

The xml is :

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;in2&gt;
	&lt;unique&gt;{{.}}&lt;/unique&gt;
	&lt;moe&gt;100%&lt;/moe&gt;
&lt;/in2&gt;

But after parsing it, the first &lt; became &amp;lt;, like this :

&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;in2&gt;
	&lt;unique&gt;something&lt;/unique&gt;
	&lt;moe&gt;100%&lt;/moe&gt;
&lt;/in2&gt;

How can I parse the xml file correctly?

This is my code :

func in2(w http.ResponseWriter, r *http.Request) {
	w.Header().Set(&quot;Content-Type&quot;, &quot;text/xml&quot;)
	t, err := template.ParseFiles(&quot;xml/in2.xml&quot;)
	if err != nil {
		fmt.Println(err)
		return
	}
	unique := &quot;something&quot;
	err = t.Execute(w, unique)
	if err != nil {
		fmt.Println(err)
	}
}

答案1

得分: 1

我不认为html/template能理解xml,所以一个xml模板会给它带来问题。如果你需要处理xml,那么http://golang.org/pkg/encoding/xml/包可能会有用。

或者你可以使用text/template,它不会关心你的xml。使用text/template的缺点是它不会有上下文意识,但是html/template也不会理解你的xml的上下文。

英文:

I don't think html/template understands xml so an xml template is going to give it problems. If you need to work with xml then the http://golang.org/pkg/encoding/xml/ package may be of use.

Or you can use text/template which won't care about your xml. The downside to using text/template is that it won't be context aware but then html/template isn't going to understand the context of your xml either.

huangapple
  • 本文由 发表于 2013年7月22日 01:28:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/17774958.html
匿名

发表评论

匿名网友

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

确定