How to create a CDATA node of xml with go?

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

    As @Tomalak mentioned, outputting CDATA is not supported.

    You can probably write ![CDATA[ as xml tag and later on replace the closing tag from the resulting xml. Will this work for you? Its probably not the one with minimal costs, but easiest. You can of course replace the MarshalIndent call with just the Marshal call in the example below.

    http://play.golang.org/p/2-u7H85-wn

    package main
    
    import (
        "encoding/xml"
        "fmt"
        "bytes"
    )
    
    type XMLProduct struct {
        XMLName          xml.Name `xml:"row"`
        ProductId        string   `xml:"product_id"`
        ProductName      string   `xml:"![CDATA["`
        OriginalPrice    string   `xml:"original_price"`
        BargainPrice     string   `xml:"bargain_price"`
        TotalReviewCount int      `xml:"total_review_count"`
        AverageScore     float64  `xml:"average_score"`
    }
    
    func main() {
        prod := XMLProduct{
            ProductId:        "ProductId",
            ProductName:      "ProductName",
            OriginalPrice:    "OriginalPrice",
            BargainPrice:     "BargainPrice",
            TotalReviewCount: 20,
            AverageScore:     2.1}
    
        out, err := xml.MarshalIndent(prod, " ", "  ")
        if err != nil {
            fmt.Printf("error: %v", err)
            return
        }
    
        out = bytes.Replace(out, []byte(""), []byte(""), []byte("]]>"), -1)
        fmt.Println(string(out))
    }
    

提交回复
热议问题