我目前正在学习如何在Android中使用Jaxb解析xml文件。但是我不知道代码中有什么错误,以及在哪里以及如何纠正它。我无法解析xml并获取食物列表。如果我删除List并将其简单地写为Food,则仅解析xml中的最后一个元素,其余似乎被覆盖。请帮我。
我正在尝试解析http://www.w3schools.com/xml/simple.xml,到目前为止,我有以下代码:
----解组XML的代码
URL url = new URL("http://www.w3schools.com/xml/simple.xml");
InputSource is = new InputSource(url.openStream());
is.setEncoding("ISO-8859-1");
JAXBContext jaxbContext = JAXBContext.newInstance(BreakfastMenu.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
BreakfastMenu menu = (BreakfastMenu)jaxbUnmarshaller.unmarshal(is);
-----这些类在----- Breakfast.java下
@XmlRootElement(name="breakfast_menu")
public class BreakfastMenu {
private List<Food> food = new ArrayList<Food>();
public List<Food> getFood() {
return food;
}
@XmlElement(name="food")
public void setFood(List<Food> food) {
this.food = food;
}
}
---食品课
@XmlRootElement(name="food")
public class Food {
private String name;
private String description;
private String calories;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
//相同的描述和卡路里
PS:我也尝试过此链接,谢谢。
解决问题感觉很好。对于可能最终遇到相同问题的其他任何人:以下是解决方案:
我将BreakfastMenu.class更改为
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="breakfast_menu")
public class BreakfastMenu {
@XmlElement(name="food", type=Food.class)
private List<Food> food = new ArrayList<Food>();
public List<Food> getFood() {
return food;
}
public void setFood(List<Food> food) {
this.food = food;
}
}
在Food.class中,我删除了@XMLElement批注,并添加了以下内容:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="food")
public class Food {
// the other declarations remain
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句