How to create a CDATA node of xml with go?

前端 未结 6 1113
自闭症患者
自闭症患者 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:35

    Expanding on the answer by @BeMasher, you can use the xml.Marshaller interface to do the work for you.

    package main
    
    import (
        "encoding/xml"
        "os"
    )
    
    type SomeXML struct {
        Unescaped CharData
        Escaped   string
    }
    
    type CharData string
    
    func (n CharData) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
        return e.EncodeElement(struct{
            S string `xml:",innerxml"`
        }{
            S: "",
        }, start)
    }
    
    func main() {
        var s SomeXML
        s.Unescaped = "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
    
    

提交回复
热议问题