2013-02-16 71 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

相關問題