DSS
DSS

Reputation: 7259

Parse nested elements in an xml using jaxb

I am currently learning how to parse xml files using Jaxb in android. But i have no clue what is wrong in the code, and where and how to correct it. I am not able to parse the xml and get the list of food items. If i remove List and simply write it as Food then only the last element in the xml is parsed, the rest seem to be overwritten. Please help me.

I am trying to parse http://www.w3schools.com/xml/simple.xml, and so far i have this code:

---- CODE FOR UNMARSHALLING THE 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);

----- The classes look as under ----- 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;
}

}

--- The food class

@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;
}

// same for description and calories

P.S: I have tried this link too Thanks.

Upvotes: 2

Views: 6834

Answers (1)

DSS
DSS

Reputation: 7259

It feels great solving the problem. To anyone else who might end up facing the same problem: here is the solution:

I changed the BreakfastMenu.class to

@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;
}
}

Whilst in the Food.class i removed the @XMLElement annotations, and added the following:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="food")
public class Food {
    // the other declarations remain
}

Upvotes: 8

Related Questions