xml.Unmarshal错误:“预期元素类型<item>但有<items>”</items> </item>

时间:2013-02-16 23:30:27

标签: go

我正在尝试解组以下XML,但收到错误。

<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)

2 个答案:

答案 0 :(得分:5)

这对我有用(请注意Items>Item):

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

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

答案 1 :(得分:2)

结构的结构与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}]}}