topskip
topskip

Reputation: 17345

XML encoding: inject XML into output

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?

Upvotes: 1

Views: 55

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109388

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.

Upvotes: 1

Related Questions