JAXB解组中XML中的命名空间问题

我有一个XML来解组JAXB。 如果我从元素中删除所有命名空间属性,但是如果我保留命名空间属性,则在解组后得到一个空对象,代码工作正常。

XML是这样的:

  kitty   kitty2   

我的动物豆是这样的:

  @XmlRootElement(name = "Animal") public class Animal{ List cats; @XmlElement(name = "Cat") public List getCats() { return cats; } public void setCats(Listcats) { this.cats= cats; } } 

Cats bean就像:

 @XmlRootElement(name = "Cat") public class Cat { private String zId; @XmlAttribute(name = "z:Id", namespace="http://schemas.microsoft.com/2003/10/Serialization/") public String getzId() { return zId; } public void setzId(String zId) { this.zId = zId; } private String name; @XmlElement(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } } 

在运行时,我得到一个空对象。 我试图从属性中删除"z:" ,我得到了这个exception:

 org.xml.sax.SAXParseException; The prefix "z" for attribute "z:Id" associated with an element type "Cat" is not bound.] 

如果我从cat和Animal中删除命名空间,我会得到以下exception:

 javax.xml.bind.UnmarshalException: unexpected element (uri:"http://allmycats.com/serviceplatform/1.0/", local:"Animal"). Expected elements are  

unmarshall的最终代码如下。 最后一行给出了空指针exception

 File file = new File(filepath1); System.out.println("file exists? : "+ file.exists()); // prints true JAXBContext jaxbContext = JAXBContext.newInstance(Animal2.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Animal2 animals = (Animal2)jaxbUnmarshaller.unmarshal( file ); System.out.println("--file size: "+animals.getCats().size()); 

我不知道如何处理我的POJO类中的命名空间和z:属性。 有什么建议吗?

如果我在XML中没有任何命名空间或任何带有命名空间的属性,但代码工作正常,但我无法改变XML。

XMLAtribute有一个属性namesape,所以

 @XmlAttribute(name = "Id", namespace="http://schemas.microsoft.com/2003/10/Serialization"). 

在通过xml判断时,cat与动物的名称空间相同

以下代码适用于JDK 7(修复了ns的动态和zid的属性名称)。

 @XmlRootElement(name = "Animal",namespace = "http://allmycats.com/serviceplatform/1.0/") public class Animal2{ List cats; @XmlElement(name = "Cat") public List getCats() { return cats; } public void setCats(Listcats) { this.cats= cats; } } @XmlRootElement(name = "Cat") public class Cat2 { private String zId; @XmlAttribute(name = "Id", namespace="http://schemas.microsoft.com/2003/10/Serialization/") public String getzId() { return zId; } public void setzId(String zId) { this.zId = zId; } private String name; @XmlElement(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } }