I'm trying to marshal an xml file and analyze or make small modifications and marshal it back out to the same format it was before. Original XML is formatted like:
<sometag>
<![CDATA[data string]]>
</sometag>
I can't marshal to that same output. I keep getting
<sometag><![CDATA[
data string
]]></sometag>
I've tried removing newlines in the xml before unmarshaling, but I do need to preserve the newlines. The software I'm exporting the marshal for is extremely picky and gives me errors if the newlines don't match.
Playground link for the code below.
package main
import (
"fmt"
"log"
"encoding/xml"
)
type structure struct {
Data struct {
XMLName xml.Name `xml:"data"`
Text string `xml:",cdata"`
}
}
func main() {
data := []byte(`<xml><data>
<![CDATA[DATA IN CDATA]]>
</data></xml>`)
fmt.Printf("%s
", string(data))
var unmarshaled structure
err := xml.Unmarshal(data, &unmarshaled)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v
", unmarshaled)
// with indent
b, err := xml.MarshalIndent(unmarshaled, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s
", string(b))
// without indent
b, err = xml.Marshal(unmarshaled)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s
", string(b))
}
I need the marshal output to be:
<![CDATA[DATA IN CDATA]]>
Not:
<![CDATA[
DATA IN CDATA
]]>