doulie0178 2013-01-07 07:24
浏览 247
已采纳

如何用go创建xml的CDATA节点?

I have the following struct:

type XMLProduct struct {
    XMLName          xml.Name `xml:"row"`
    ProductId        string   `xml:"product_id"`
    ProductName      string   `xml:"product_name"`
    OriginalPrice    string   `xml:"original_price"`
    BargainPrice     string   `xml:"bargain_price"`
    TotalReviewCount int      `xml:"total_review_count"`
    AverageScore     float64  `xml:"average_score"`
}

And I use the encoding/xml to encode this and then display it on web page.

The ProductName field needs to be enclosed with <![CDATA[]]. But if I write it as <![CDATA[ + p.ProductName + ]]>, the < and > will be translated to &lt; and &gt;.

How can I create the CDATA at minimal cost?

  • 写回答

6条回答 默认 最新

  • dsd119120 2013-01-07 15:28
    关注

    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("<![CDATA[>"), []byte("<![CDATA["), -1)
        out = bytes.Replace(out, []byte("</![CDATA[>"), []byte("]]>"), -1)
        fmt.Println(string(out))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号