2012-07-10 51 views
2

解组通用的孩子,我有格式的XML文件: -使用JAXB

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

我使用JAXB解组XML,并有一类设置为比“item_attribute的孩子其他每个元素”。我想一般地解组每个'item_attribute'元素中的数据(元素名称和元素值),而不知道元素被调用的是什么。

我所知道的是'item_attribute'总是只有1个子元素,并且该子元素可以被调用并包含任何东西。

我试着使用:

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; 
    } 

} 

但它一直抛出illegalannotationexception!

+0

我认为你应该使用'Integer',而不是'int' – oshai 2012-07-14 20:55:49

回答

0

如果您注释字段(实例变量),你需要添加以下类型级别的注释:

@XmlAccessorType(XmlAccessType.FIELD) 
public class Foo { 

    @XmlAnyElement(lax = true) 
    private Object data; 

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

} 

或者你可以把注释上的get方法。

public class Foo { 

    private Object data; 

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

} 
+0

您好我试过这个,它没有工作 - 它仍然抛出相同的错误 – user1155083 2012-07-10 12:58:29

+0

@ user1155083 - 你可以发布堆栈跟踪? – 2012-07-10 13:01:05

+0

com.sun.xml.bind.v2.runtime.IllegalAnnotationsException:1个IllegalAnnotationExceptions的计数 javax.xml.bind.JAXBElement没有无参数默认构造函数。 – user1155083 2012-07-10 13:07:33

0

添加@XmlAnyElement(LAX =真)的每一个错误(javax.xml.bind.JAXBElement没有默认的构造函数)

+0

多一点解释可能会帮助程序员了解它是如何工作的。 – Daenarys 2014-06-02 14:16:40