我的XML文档如下,
<Configuration>
<Shop>
<Level>1</Level>
<Block>
<Items>
<Item>Basic</Item>
</Items>
</Block>
</Shop>
<Shop>
<Level>2</Level>
<Block>
<Items>
<Item>Basic</Item>
<Item>Pin</Item>
</Items>
</Block>
</Shop></Configuration>
并有如下课程,
@XmlRootElement(name = "Configuration")
class ShopConfig {
private List<Shop> shops;
@XmlElementWrapper(name = "Configuration", nillable = false)
@XmlElement(name = "Shop", nillable = false)
public List<Shop> getShops() {
return shops;
}
public void setShops(List<Shop> shops) {
this.shops = shops;
}
public void print(){
for(Shop shop: shops){
List<String> l = shop.getItemNames();
for(String s : l){
System.out.println(s);
}
}
}
}
public class Shop {
private String level;
private List<String> itemNames;
public String getLevel() {
return level;
}
@XmlElement(name = "Level")
public void setLevel(String level) {
this.level = level;
}
@XmlElementWrapper(name = "Items", nillable = false)
@XmlElement(name = "Item", nillable = false)
public List<String> getItemNames() {
return itemNames;
}
public void setItemNames(List<String> itemNames) {
this.itemNames = itemNames;
}
}
我按照以下方式解组xml,
private static ShopConfig initShopConfig() throws JAXBException {
String configPath = "Config.xml";
File file = new File(configPath);
JAXBContext ctx = JAXBContext.newInstance(ShopConfig.class);
Unmarshaller um = ctx.createUnmarshaller();
return (ShopConfig) um.unmarshal(file);
}
但是当我尝试打印时,当我尝试调用print方法时,会给出NPE,说shop变量为null。这意味着它没有正确地解散。我在这做什么错?
public static void main(String args[]){
ShopConfig l = (ShopConfig)ConfigLoader.getInstance().getConfig();
l.print();
}
该例外不具备信息,
Exception in thread "main" java.lang.NullPointerException
at config.ShopConfig.print(ShopConfig.java:42)
at config.Test.main(Test.java:9)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)