I wonder if anyone can help, I have the following xml file, the problem is I can not see the third node ‘food’. I have created the files using JAXB there are four files have been created ObjectFactory, Breakfast-menu, foodType and food. I can get to foodType from Breakfast-menu and see the name(fresh and frozen) but not ‘food’ and it’s content. can some please give some ideas.
thanks
<Breakfast-menu>
<foodType>
<name>fresh</name>
<food name="Milk">
<price>2</price>
</food>
<food name="Pears">
<price>3</price>
</food>
<food name="Apples">
<price>1</price>
</food>
</foodType>
<foodType>
<name>frozen</name>
<food name="Fish">
<price>2</price>
</food>
<food name="chips">
<price>1</price>
</food>
</foodType>
</Breakfast-menu>
Java
JAXBContext jaxbContext = JAXBContext.newInstance("food");
Unmarshaller u = jaxbContext.createUnmarshaller();
BreakfastMenu bM = (BreakfastMenu) u.unmarshal(
new FileInputStream( "C:\\Users\\food.xml" ));
List<FoodType> tType = bM.getFoodType();
for (FoodType tT : tType) {
System.out.println("\t" + tT.getFood());
}
Since this use case has a very simple XML document I would recommend starting from Java objects.
BreakfastMenu
JAXB (JSR-222) is configuration by exception so you only need to add annotations where you want the binding to differ from the default (see: http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html).
FoodType
By default the mappings are based on the public properties, but we can change JAXB to use fields with the
@XmlAccessorType(XmlAccessType.FIELD)annotation (see: http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html).Food
Demo