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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.