英文:
XML encoding: inject XML into output
问题
我有一个包含XML片段的字符串,我想将其注入到编码流中:
package main
import (
"encoding/xml"
"os"
)
func main() {
myxml := `<mytag>foo</mytag>`
enc := xml.NewEncoder(os.Stdout)
root := xml.StartElement{Name: xml.Name{Local: "root"}}
enc.EncodeToken(root)
enc.EncodeToken(xml.CharData(myxml))
enc.EncodeToken(root.End())
enc.Flush()
}
我得到的结果是<root>&lt;mytag&gt;foo&lt;/mytag&gt;</root>
,但我想要的是<root><mytag>foo</mytag></root>
有没有办法使用enc.EncodeToken()
或类似的方法来实现这个目标?
英文:
I have a string with an XML fragment and I'd like to inject it into the encoding stream:
package main
import (
"encoding/xml"
"os"
)
func main() {
myxml := `<mytag>foo</mytag>`
enc := xml.NewEncoder(os.Stdout)
root := xml.StartElement{Name: xml.Name{Local: "root"}}
enc.EncodeToken(root)
enc.EncodeToken(xml.CharData(myxml))
enc.EncodeToken(root.End())
enc.Flush()
}
I get <root>&lt;mytag&gt;foo&lt;/mytag&gt;</root>
but I'd like to have <root><mytag>foo</mytag></root>
Is there any way I can do this using enc.EncodeToken()
or something similiar?
答案1
得分: 1
插入原始XML的唯一方法是直接将其写入流中,例如在此情况下是os.Stdout。
myxml := `<mytag>foo</mytag>`
enc := xml.NewEncoder(os.Stdout)
root := xml.StartElement{Name: xml.Name{Local: "root"}}
enc.EncodeToken(root)
enc.Flush()
os.Stdout.WriteString(myxml)
enc.EncodeToken(root.End())
enc.Flush()
这基本上就是如果使用innerxml
结构标签会发生的情况,但是那只能通过结构体来完成,并且会在原始XML周围给你多一组表示结构体的标签。
英文:
The only way to insert raw XML is to write it directly to the stream, os.Stdout in this case.
myxml := `<mytag>foo</mytag>`
enc := xml.NewEncoder(os.Stdout)
root := xml.StartElement{Name: xml.Name{Local: "root"}}
enc.EncodeToken(root)
enc.Flush()
os.Stdout.WriteString(myxml)
enc.EncodeToken(root.End())
enc.Flush()
This is essentialy what happens if you use the innerxml
struct tag, but that can only be done through a struct, and would give you one more set of tags representing the struct around your raw xml.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论