5

我正在尝试解组以下 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)
4

2 回答 2

6

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

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

type Product struct {
    ASIN   string `xml:"ASIN"`
}
于 2013-02-17T10:08:53.530 回答
2

struct 的结构与 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}]}}
于 2013-02-17T02:36:06.837 回答