I try to unmarshal a XML file using xml.Unmarshal of "encoding/xml" package.
The XML file starts like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>frames</key>
<dict>
<key>0</key>
<dict>
<key>frame</key>
<string>{{0, 0}, {81, 145}}</string>
<key>offset</key>
<string>{0, 0}</string>
<key>rotated</key>
<false/>
<key>sourceColorRect</key>
<string>{{0, 0}, {80, 145}}</string>
<key>sourceSize</key>
<string>{81, 145}</string>
<key>aliases</key>
<array>
</array>
</dict>
<key>1</key>
I define two structs:
// types for createfont command
type Characters struct {
XMLName xml.Name `xml:"dict"`
Char []string `xml:"key"`
}
type Result struct {
Plist string `xml:"plist"`
XMLName xml.Name `xml:"dict"`
Keys []string `xml:"key"`
Chars []Characters `xml:"dict"`
}
And unmarshal with this:
v := Result{}
err = xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
} else {
fmt.Println("Result",v)
}
As result I get:
error: expected element type <dict> but have <plist>
If I remove the plist line in the XML file and in the struct it works fine.
How do I have to write, that I can let it in?
The order of your XMLName
field within your struct is irrelevant. Unmarshalling happens only with regard to the field names and the tags not order.
By having XMLName
anywhere in your type you are declaring the entire type should be of/within that XML element.