go 1.8 xml解析不支持cdata

go 1.8 xml解析不支持cdata, 但是go1.2是支持的,这是bug?

package main

import (
    "encoding/xml"
    "fmt"
    "runtime"
)

type WechatNotifyInfo struct {
    XMLName        xml.Name `xml:"xml"`
    Appid          string `xml:"appid,cdata"`
}

var Text =
    `<xml>
    <appid><![CDATA[wx0f0df4fda4ff1937]]></appid>
    </xml>
    `

func main() {
    fmt.Println("version", runtime.Version())

    msg := &WechatNotifyInfo{}
    err := xml.Unmarshal([]byte(Text), msg)
    if err != nil{
        fmt.Println(err)
    }

    fmt.Println(fmt.Sprintf("%#v", msg))
}

这个是go1.8运行结果

version go1.8
xml: invalid tag in field Appid of type main.WechatNotifyInfo: "appid,cdata"
&main.WechatNotifyInfo{XMLName:xml.Name{Space:"", Local:""}, Appid:""}

这个是go1.2.1运行结果

version go1.2.1
&main.WechatNotifyInfo{XMLName:xml.Name{Space:"", Local:"xml"}, Appid:"wx0f0df4fda4ff1937"}
已邀请:

hmly

赞同来自: stirlingx

我试了一下,把cdata改成大写就可以了。

package main

import (
    "encoding/xml"
    "fmt"
    "runtime"
)

type WechatNotifyInfo struct {
    XMLName xml.Name `xml:"xml"`
    Appid   string   `xml:"appid,CDATA"` //cdata改成大写
}

var Text = `<xml>
    <appid><![CDATA[wx0f0df4fda4ff1937]]></appid>
    </xml>
    `

func main() {
    fmt.Println("version", runtime.Version())

    msg := &WechatNotifyInfo{}
    err := xml.Unmarshal([]byte(Text), msg)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(fmt.Sprintf("%#v", msg))
}

stirlingx - https://github.com/liyue201

赞同来自:

然后改成这样子可以正确解析

package main

import (
    "encoding/xml"
    "fmt"
    "runtime"
)

type WechatNotifyInfo struct {
    XMLName        xml.Name `xml:"xml"`
    Appid           CDATA  `xml:"appid"`
}

var Text =
    `<xml>
    <appid><![CDATA[wx0f0df4fda4ff1937]]></appid>
    </xml>
    `

type CDATA struct {
    Text string `xml:",cdata"`
}

func main() {
    fmt.Println("version", runtime.Version())

    msg := &WechatNotifyInfo{}
    err := xml.Unmarshal([]byte(Text), msg)
    if err != nil{
        fmt.Println(err)
    }

    fmt.Println(fmt.Sprintf("%#v", msg))
}
version go1.8
&main.WechatNotifyInfo{XMLName:xml.Name{Space:"", Local:"xml"}, Appid:main.CDATA{Text:"wx0f0df4fda4ff1937"}}

要回复问题请先登录注册