英文:
xml.Unmarshal error: expected element type <dict> but have <plist>
问题
我尝试使用"encoding/xml"包中的xml.Unmarshal函数来解析XML文件。
XML文件的开头如下所示:
<?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>
我定义了两个结构体:
// 用于createfont命令的类型
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"`
}
并使用以下代码进行解析:
v := Result{}
err = xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
} else {
fmt.Println("Result",v)
}
结果显示:
error: expected element type <dict> but have <plist>
如果我在XML文件和结构体中删除plist行,则可以正常工作。
我应该如何编写代码,才能保留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
得分: 0
你的XMLName
字段在结构体中的顺序是无关紧要的。解组只与字段名称和标签有关,而与顺序无关。
只要在类型中的任何位置有XMLName
,就表示整个类型应该是该XML元素的一部分。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论