2013-02-16 70 views
3

我想解组以下XML,但收到错误。xml.Unmarshal错误:“期望元素类型<Item>但具有<Items>”

<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01"> 
<Items> 
<Item> 
<ASIN>B005XSS8VC</ASIN> 
</Item> 
</Items> 

这里是我的结构:

type Product struct { 
    XMLName xml.Name `xml:"Item"` 
    ASIN string 
} 

type Result struct { 
    XMLName xml.Name `xml:"ItemSearchResponse"` 
    Products []Product `xml:"Items"` 
} 

错误的文本是“预期的元素类型<Item>但有<Items>,”但我不能看到我要去哪里错误。任何帮助表示赞赏。

v := &Result{Products: nil} 
err = xml.Unmarshal(xmlBody, v) 

回答

3

这对我的作品(注意Items>Item):

type Result struct { 
XMLName  xml.Name `xml:"ItemSearchResponse"` 
Products  []Product `xml:"Items>Item"` 
} 

type Product struct { 
    ASIN string `xml:"ASIN"` 
} 
1

的结构不与XML结构相匹配的结构,这里是一个工作代码:

package main 

import (
    "encoding/xml" 
    "log" 
) 

type Product struct { 
    ASIN string `xml:"ASIN"` 
} 
type Items struct { 
    Products []Product `xml:"Item"` 
} 

type Result struct { 
    XMLName xml.Name `xml:"ItemSearchResponse"` 
    Items Items `xml:"Items"` 
} 

func main() { 
    xmlBody := `<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01"> 
<Items> 
<Item> 
<ASIN>B005XSS8VC</ASIN> 
</Item> 
<Item> 
<ASIN>C005XSS8VC</ASIN> 
</Item> 
</Items>` 
    v := &Result{} 
    err := xml.Unmarshal([]byte(xmlBody), v) 
    log.Println(err) 
    log.Printf("%+v", v) 

} 

它会输出:

&{XMLName:{Space:http://webservices.amazon.com/AWSECommerceService/2011-08-01 Local:ItemSearchResponse} Products:{Products:[{ASIN:B005XSS8VC} {ASIN:C005XSS8VC}]}} 
+0

我以为“xml:...”标签的全部要点是结构的结构不需要与XML的结构相匹配。这是有道理的,并解释了为什么我的解决方案如下(因为使用项目>项目“跳过”项目结构)。 – 2013-02-17 10:06:58

相关问题