How to create a CDATA node of xml with go?

前端 未结 6 1050
自闭症患者
自闭症患者 2021-02-19 09:03

I have the following struct:

type XMLProduct struct {
    XMLName          xml.Name `xml:\"row\"`
    ProductId        string   `xml:\"product_id\"`
    ProductN         


        
6条回答
  •  清歌不尽
    2021-02-19 09:39

    I'm not sure which version of go the innerxml tag became available in, but it allows you to include data which won't be escaped:

    Code:

    package main
    
    import (
        "encoding/xml"
        "os"
    )
    
    type SomeXML struct {
        Unescaped CharData
        Escaped   string
    }
    
    type CharData struct {
        Text []byte `xml:",innerxml"`
    }
    
    func NewCharData(s string) CharData {
        return CharData{[]byte("")}
    }
    
    func main() {
        var s SomeXML
        s.Unescaped = NewCharData("http://www.example.com/?param1=foo¶m2=bar")
        s.Escaped = "http://www.example.com/?param1=foo¶m2=bar"
        data, _ := xml.MarshalIndent(s, "", "\t")
        os.Stdout.Write(data)
    }
    

    Output:

    
        
        http://www.example.com/?param1=foo&param2=bar
    
    

提交回复
热议问题