我目前正在学习如何在 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);
----- 类如下所示 ----- 早餐.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;
}
//描述和卡路里相同
P.S: 我试过了this link too 谢谢。
最佳答案
解决问题的感觉真好。对于可能最终面临同样问题的任何其他人:这是解决方案:
我将 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
}
关于java - 使用 jaxb 解析 xml 中的嵌套元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19199995/