duangan6636 2019-09-12 05:34
浏览 137

如何使用换行符将godata中的CDATA封送与输入数据相同

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
]]>
  • 写回答

1条回答 默认 最新

  • dongyan6235 2019-09-12 05:52
    关注

    One option you could try is to use ",innerxml" instead of ",cdata". However, that will leave the string field as raw XML, and will have CDATA in it. If this is something you can work with, then that's an option. If not, then I don't think there's a way to get this right with XML unmarshaling. It will normalize the cdata into a single continuous string, and will lose the exact location of the CDATA markup. You might have more luck if you used the xml.Decoder.

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类