, but has " I am trying to unmount the following XML but I am getting an error.

Xml.Unmarshal error: "expected item type is <Item>, but has <Items>"

I am trying to unmount the following XML but I am getting an error.

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

      

Here are my structures:

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

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

      

The error text is "expected element type <Item>

but has <Items>

" but I can't see where I am going wrong. Any help is appreciated.

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

      

+3


source to share


2 answers


This works for me (please note Items>Item

):



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

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

      

+3


source


The structure structure does not match the xml structure, here is the working code:

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)

}

      



it will output:

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

      

+1


source







All Articles