How to create a CDATA node of xml with go?

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

    @spirit-zhang: since Go 1.6, you can now use ,cdata tags:

    package main
    
    import (
        "fmt"
        "encoding/xml"
    )
    
    type RootElement struct {
        XMLName xml.Name `xml:"root"`
        Summary *Summary `xml:"summary"`
    }
    
    type Summary struct {
        XMLName xml.Name `xml:"summary"`
        Text    string   `xml:",cdata"`
    }
    
    func main() {
    
        cdata := `My Example Website`
        v := RootElement{
            Summary: &Summary{
                Text: cdata,
            },
        }
    
        b, err := xml.MarshalIndent(v, "", "  ")
        if err != nil {
            fmt.Println("oopsie:", err)
            return
        }
        fmt.Println(string(b))
    }
    

    Outputs:

    
      My Example Website]]>
    
    

    Playground: https://play.golang.org/p/xRn6fe0ilj

    The rules are basically: 1) it has to be ,cdata, you can't specify the node name and 2) use the xml.Name to name the node as you want.

    This is how most of the custom stuff for Go 1.6+ and XML works these days (embedded structs with xml.Name).


    EDIT: Added xml:"summary" to the RootElement struct, so you can you can also Unmarshal the xml back to the struct in reverse (required to be set in both places).

提交回复
热议问题