duanmao1932
duanmao1932
2018-03-27 09:12
浏览 299

使用Go使用CDATA解析XML

I am new in Golang and I've been trying to parse an xml in Go by defining structs and using xml.Unmarshal.There's no error thrown but the struct is empty. this is my xml:

var bodyXML = []byte('<?xml version="1.0" encoding="ISO-8859-1"?>
<smsBatchResponse>
 <ok>
  <![CDATA[CHECK_OK]]>
 </ok>
</smsBatchResponse>')

and this is my code:

type SmsBatchResponse struct {
    Ok string `xml:"ok"`
}

var result SmsBatchResponse

xml.Unmarshal(bodyXML,result)
fmt.Println(result)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doucheng7234
    doucheng7234 2018-03-27 09:35
    已采纳

    The first thing you should do is not ignore any errors that xml.Unmarshal can give you:

    if err := xml.Unmarshal(bodyXML, result); err != nil {
        fmt.Println(err)
    }
    

    This will (eventually) give you a number of errors:

    Error number 1: By default, the XML decoder wants the XML to be encoded in UTF-8. You are providing ISO-8859-1. This can either be trivially fixed by changing your XML encoding to UTF-8; or by manually creating a xml.Decoder and settings the CharsetReader member.

    Error number 2: When unmarshalling, the XML decoder expects a pointer, because it needs to modify the passed in struct:

    if err := xml.Unmarshal(bodyXML, &result); err != nil {
        ....
    }
    

    Note the & in front of result.

    When you fix these errors, the XML unmarshals fine.

    I have created a fully working example on the Go Playground

    点赞 评论

相关推荐