【发布时间】:2015-04-25 00:48:32
【问题描述】:
我有一个要解组的简单 xml。但我在输出中只得到一个空列表。不抛出异常。 这是第三方生成的 xml,我需要在不更改 xml 的情况下完成这项工作。
XML:
<Animal xmlns="http://allmycats.com/serviceplatform/1.0/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Cat z:Id="i1" 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>
Animal 的 POJO bean:
@XmlRootElement(name = "Animal",namespace = "http://allmycats.com/serviceplatform/1.0/")
public class Animal{
List<Cat> cats;
@XmlElement(name = "Cat")
public List<Cat> getCats() {
return cats;
}
public void setCats(List<Cat>cats) {
this.cats= cats;
}
}
Cat 的 POJO bean
@XmlRootElement(name = "Cat")
public class Cat {
private String zId;
private String name;
@XmlAttribute(name = "Id", namespace="http://schemas.microsoft.com/2003/10/Serialization/")
public String getzId() {
return zId;
}
public void setzId(String zId) {
this.zId = zId;
}
@XmlElement(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
解组码是:
File file = new File(filepath);
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());
最后一行给出了一个空指针异常。
我在 BEAN 类中的命名空间有什么问题吗?我是 Jaxb 的新手,这个问题困扰了我 3 天! 我之前问过这个问题,但无法得到正确的答案,这是一个更准确的问题。
【问题讨论】:
-
@Zielu .. 是的,它是重复的,但也许我的问题之前并不清楚,解决方案没有奏效。因此,我用干净的代码和 xml 再次询问它。感谢您的 cmets,但我仍然遇到这个问题。
标签: java xml jaxb xml-namespaces unmarshalling