douxiuyu2028 2015-03-08 09:38
浏览 54
已采纳

xml.Unmarshal错误:预期元素类型为<dict>但具有<plist>

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?

  • 写回答

1条回答 默认 最新

  • duangong0690 2015-03-08 18:37
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?