英文:
Using encoding/xml.Encoder how do I place the xml header on its own line?
问题
我有以下使用xml.Encode
的代码。
package main
import (
"bytes"
"encoding/xml"
"fmt"
)
type Stuff struct {
Name string `xml:"name"`
}
func main() {
w := &bytes.Buffer{}
enc := xml.NewEncoder(w)
enc.Indent("", " ")
procInst := xml.ProcInst{
Target: "xml",
Inst: []byte("version=\"1.0\" encoding=\"UTF-8\""),
}
if err := enc.EncodeToken(procInst); err != nil {
panic(err)
}
if err := enc.Encode(Stuff{"My stuff"}); err != nil {
panic(err)
}
fmt.Println(w.String())
}
它输出:
<?xml version="1.0" encoding="UTF-8"?><Stuff>
<name>My stuff</name>
</Stuff>
我该如何使它在新的一行上打印<Stuff>
开始标签:
<?xml version="1.0" encoding="UTF-8"?>
<Stuff>
<name>My stuff</name>
</Stuff>
很不幸,我需要在这里写更多的内容才能提交问题。不太确定要写什么,因为我认为上面的解释已经足够了。
英文:
I have the following code that uses xml.Encode
.
package main
import (
"bytes"
"encoding/xml"
"fmt"
)
type Stuff struct {
Name string `xml:"name"`
}
func main() {
w := &bytes.Buffer{}
enc := xml.NewEncoder(w)
enc.Indent("", " ")
procInst := xml.ProcInst{
Target: "xml",
Inst: []byte("version=\"1.0\" encoding=\"UTF-8\""),
}
if err := enc.EncodeToken(procInst); err != nil {
panic(err)
}
if err := enc.Encode(Stuff{"My stuff"}); err != nil {
panic(err)
}
fmt.Println(w.String())
}
http://play.golang.org/p/ZtZ5FGABmj
It prints:
<?xml version="1.0" encoding="UTF-8"?><Stuff>
<name>My stuff</name>
</Stuff>
How do I make it print with the <Stuff>
start tag on a new line:
<?xml version="1.0" encoding="UTF-8"?>
<Stuff>
<name>My stuff</name>
</Stuff>
Unfortunately I need to write more here so that I can submit the question. Not really sure what to write though because I believe my question is summarized adequately with the above explanation.
答案1
得分: 8
你可以自己写一行带有换行符的静态代码。这是一个示例:
w := &bytes.Buffer{}
w.Write([]byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"))
enc := xml.NewEncoder(w)
enc.Indent("", " ")
if err := enc.Encode(Stuff{"My stuff"}); err != nil {
panic(err)
}
fmt.Println(w.String())
这一行甚至在xml
包中被定义为一个常量,所以你可以直接写:
w := &bytes.Buffer{}
w.WriteString(xml.Header)
你可以在以下链接中查看示例代码:
英文:
How about just write that one static line with a newline character yourself? Go Playground
w := &bytes.Buffer{}
w.Write([]byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"))
enc := xml.NewEncoder(w)
enc.Indent("", " ")
if err := enc.Encode(Stuff{"My stuff"}); err != nil {
panic(err)
}
fmt.Println(w.String())
This one line is even defined as a constant in the xml
package, so you can simply write: Go Playground
w := &bytes.Buffer{}
w.WriteString(xml.Header)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论