简体   繁体   中英

Unmarshalling generic child using Jaxb

I have an xml file in the format:-

<item>
    <item_attribute index="1" type="1" >
        <name>value1</name>
    </item_attribute>
    <item_attribute index="2" type="1" >
        <a_differnt_name>value2</a_different_name>
    </item_attribute>
    <item_attribute index="5" type="2" >
        <another_name>value3</another_name>
    </item_attribute>
</item>

I am using JAXB to unmarshall the xml and have a class set up for each element other than the child of the 'item_attribute'. I want to generically unmarshall the data (element name and element value) within each 'item_attribute' element without knowing what the element is called.

All I know is the 'item_attribute' always has only 1 child element and that child could be called and contain anything.

I tried using:

public class Item_attribute {

    private int index;
    private Object data;

    @XmlAttribute(name = "index")
    public int getIndex() {
        return index;
    }
    public void setIndex(int index) {
        this.index = index;
    }

    @XmlAnyElement(lax = true)
    public Object getData() {
        return this.data;
    }

}

but it keeps throwing an illegalannotationexception!

If you annotate the field (instance variable) you need to add the following type level annotation:

@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {

    @XmlAnyElement(lax = true)
    private Object data;

     public Object getData() {  
          return this.data;
     }

}

Or you can put the annotation on the get method.

public class Foo {

    private Object data;

     @XmlAnyElement(lax=true)
     public Object getData() {  
          return this.data;
     }

}

将@XmlAnyElement(lax = true)添加到每个错误中(javax.xml.bind.JAXBElement没有默认的构造函数)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM