XML编码:将XML注入输出中

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

XML encoding: inject XML into output

问题

我有一个包含XML片段的字符串,我想将其注入到编码流中:

  1. package main
  2. import (
  3. "encoding/xml"
  4. "os"
  5. )
  6. func main() {
  7. myxml := `<mytag>foo</mytag>`
  8. enc := xml.NewEncoder(os.Stdout)
  9. root := xml.StartElement{Name: xml.Name{Local: "root"}}
  10. enc.EncodeToken(root)
  11. enc.EncodeToken(xml.CharData(myxml))
  12. enc.EncodeToken(root.End())
  13. enc.Flush()
  14. }

我得到的结果是&lt;root&gt;&amp;lt;mytag&amp;gt;foo&amp;lt;/mytag&amp;gt;&lt;/root&gt;,但我想要的是&lt;root&gt;&lt;mytag&gt;foo&lt;/mytag&gt;&lt;/root&gt;

有没有办法使用enc.EncodeToken()或类似的方法来实现这个目标?

英文:

I have a string with an XML fragment and I'd like to inject it into the encoding stream:

  1. package main
  2. import (
  3. &quot;encoding/xml&quot;
  4. &quot;os&quot;
  5. )
  6. func main() {
  7. myxml := `&lt;mytag&gt;foo&lt;/mytag&gt;`
  8. enc := xml.NewEncoder(os.Stdout)
  9. root := xml.StartElement{Name: xml.Name{Local: &quot;root&quot;}}
  10. enc.EncodeToken(root)
  11. enc.EncodeToken(xml.CharData(myxml))
  12. enc.EncodeToken(root.End())
  13. enc.Flush()
  14. }

I get &lt;root&gt;&amp;lt;mytag&amp;gt;foo&amp;lt;/mytag&amp;gt;&lt;/root&gt; but I'd like to have &lt;root&gt;&lt;mytag&gt;foo&lt;/mytag&gt;&lt;/root&gt;

Is there any way I can do this using enc.EncodeToken() or something similiar?

答案1

得分: 1

插入原始XML的唯一方法是直接将其写入流中,例如在此情况下是os.Stdout。

  1. myxml := `<mytag>foo</mytag>`
  2. enc := xml.NewEncoder(os.Stdout)
  3. root := xml.StartElement{Name: xml.Name{Local: "root"}}
  4. enc.EncodeToken(root)
  5. enc.Flush()
  6. os.Stdout.WriteString(myxml)
  7. enc.EncodeToken(root.End())
  8. enc.Flush()

这基本上就是如果使用innerxml结构标签会发生的情况,但是那只能通过结构体来完成,并且会在原始XML周围给你多一组表示结构体的标签。

英文:

The only way to insert raw XML is to write it directly to the stream, os.Stdout in this case.

  1. myxml := `&lt;mytag&gt;foo&lt;/mytag&gt;`
  2. enc := xml.NewEncoder(os.Stdout)
  3. root := xml.StartElement{Name: xml.Name{Local: &quot;root&quot;}}
  4. enc.EncodeToken(root)
  5. enc.Flush()
  6. os.Stdout.WriteString(myxml)
  7. enc.EncodeToken(root.End())
  8. 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.

huangapple
  • 本文由 发表于 2015年11月6日 01:33:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/33551110.html
匿名

发表评论

匿名网友

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

确定