尝试将XML映射到POJO时出现“意外元素”

时间:2014-03-06 00:51:22

标签: java xml jaxb

我正在尝试使用JAXB将以下XML映射到POJO,以便我可以使用XML中的数据,但是,我收到以下错误:

! javax.xml.bind.UnmarshalException: unexpected element 
(uri:"http://webservices.amazon.com/AWSECommerceService/2011-08-01", 
local:"ItemSearchResponse"). Expected elements are <{}ItemSearchResponse>

XML:

<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">
    <Items>
        <Item>
            <ASIN>B001DJLCRC</ASIN>
            <DetailPageURL>
                http://www.amazon.com/Breaking-Bad-Complete-First-Season/dp/B001DJLCRC%3FSubscriptionId%3DAKIAJ6JZ43XIWIUIIQLA%26tag%3Dsample026-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB001DJLCRC
            </DetailPageURL>
            <ItemLinks>
                <ItemLink>
                    <Description>Technical Details</Description>
                    <URL>
                        http://www.amazon.com/Breaking-Bad-Complete-First-Season/dp/tech-data/B001DJLCRC%3FSubscriptionId%3DAKIAJ6JZ43XIWIUIIQLA%26tag%3Dsample026-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB001DJLCRC
                    </URL>
                </ItemLink>
            </ItemLinks>
            <ItemAttributes>
                <Actor>Bryan Cranston</Actor>
                <Actor>Aaron Paul</Actor>
                <Manufacturer>Sony Pictures Home Entertainment</Manufacturer>
                <ProductGroup>DVD</ProductGroup>
                <Title>Breaking Bad: The Complete First Season</Title>
            </ItemAttributes>
        </Item>
    </Items>
</ItemSearchResponse>

我的POJO(故意跳过getter / setter)

ItemSearchResponse

@XmlRootElement(name="ItemSearchResponse")
@XmlAccessorType(XmlAccessType.FIELD)
public class ItemSearchResponse
{
    @XmlElement(name="Items")
    private Items items = null;
}

@XmlAccessorType(XmlAccessType.FIELD)
public class Items {
    @XmlElement(name="Item")
    List<Item> items = new ArrayList();
}

物品

@XmlAccessorType(XmlAccessType.FIELD)
public class Item {
    @XmlElement(name="ASIN")
    private String asin;
    @XmlElement(name="ItemAttributes")
    private ItemAttributes attributes;
}

项目属性

@XmlAccessorType(XmlAccessType.FIELD)
public class ItemAttributes {
    @XmlElement(name="Title")
    private String title;
    @XmlElement(name="Author")
    private String author;
}

问题

  • 如何解决错误?我的POJO设置不正确吗?如果是这样,我应该如何重组POJO?

  • xml中有多个Author。如何将它们映射到数组或排序列表。

1 个答案:

答案 0 :(得分:1)

您需要使用包级别@XmlSchema注释来映射模型的命名空间限定。

<强> package-info.java

@XmlSchema( 
    namespace = "http://www.example.org/package", 
    elementFormDefault = XmlNsForm.QUALIFIED) 
package example;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

了解更多信息