英文:
Go: After parse xml file with template.ParseFiles, the first "<" became "<"
问题
我正在尝试使用template.ParseFiles()解析一个xml文件。
xml文件如下:
<?xml version="1.0" encoding="utf-8"?>
<in2>
	<unique>{{.}}</unique>
	<moe>100%</moe>
</in2>
但是在解析后,第一个<变成了&lt;,如下所示:
&lt;?xml version="1.0" encoding="utf-8"?>
<in2>
	<unique>something</unique>
	<moe>100%</moe>
</in2>
我该如何正确解析xml文件?
这是我的代码:
func in2(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/xml")
	t, err := template.ParseFiles("xml/in2.xml")
	if err != nil {
		fmt.Println(err)
		return
	}
	unique := "something"
	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 :
<?xml version="1.0" encoding="utf-8"?>
<in2>
	<unique>{{.}}</unique>
	<moe>100%</moe>
</in2>
But after parsing it, the first < became &lt;, like this :
&lt;?xml version="1.0" encoding="utf-8"?>
<in2>
	<unique>something</unique>
	<moe>100%</moe>
</in2>
How can I parse the xml file correctly?
This is my code :
func in2(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/xml")
	t, err := template.ParseFiles("xml/in2.xml")
	if err != nil {
		fmt.Println(err)
		return
	}
	unique := "something"
	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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论