我有一个XML来解组JAXB。如果我从元素中删除所有命名空间属性,但是如果我保留命名空间属性,则在解组后我得到一个空对象,代码工作正常。
XML是这样的:
<Animal xmlns="http://allmycats.com/serviceplatform/1.0/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Cat z:Id="i3" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
<name>kitty</name>
</Cat>
<Cat z:Id="i2" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
<name>kitty2</name>
</Cat>
</Animal>
我的动物豆是这样的:
@XmlRootElement(name = "Animal")
public class Animal{
List<Cat> cats;
@XmlElement(name = "Cat")
public List<Cat> getCats() {
return cats;
}
public void setCats(List<Cat>cats) {
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:"
,我得到了这个例外:
org.xml.sax.SAXParseException; The prefix "z" for attribute "z:Id" associated with an element type "Cat" is not bound.]
如果我从cat和Animal中删除命名空间,我会遇到以下异常:
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://allmycats.com/serviceplatform/1.0/", local:"Animal"). Expected elements are <{}Animal>
unmarshall的最终代码如下。最后一行给出了空指针异常
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,那么代码可以正常工作。
答案 0 :(得分:2)
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<Cat2> cats;
@XmlElement(name = "Cat")
public List<Cat2> getCats() {
return cats;
}
public void setCats(List<Cat2>cats) {
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;
}
}