Iterate through elements in JAXB

I created a method for unmarshall my xml (item.xml) file. But if there are multiple elements, how can I iterate over all the elements and display them? My code is as follows: final JAXBContext jc = JAXBContext.newInstance ("com.generated");

final Unmarshaller u = jc.createUnmarshaller(); final File f = new File("D:\\item.xml"); final JAXBElement element = (JAXBElement) u.unmarshal(f); final Item item = (Item) element.getValue(); // This will be helpful only if the xml contains one element System.out.println(item.getCode()); System.out.println(item.getName()); System.out.println(item.getPrice()); 

If my xml

  <item> <item1> <code>12000</code> <name>Samsung Galaxy Tab 620</name> <price>9999</price> </item1> <item2> <code>15000</code> <name>NOKIA</name> <price>19999</price> </item2> <item3> <code>18000</code> <name>HTC 620</name> <price>29999</price> </item3> </item> How can i get all the vaues displayed?Can anyone help me? 
+4
source share
2 answers

I used JAXB in some projects at the university. As far as I remember, you should return an object, for example, ItemList , and then request this object to retrieve the contained elements.

So your xml should look something like this:

 <itemlist> <item> <code>..</code> <name>..</name> <price>..</price> </item> <item> <code>..</code> <name>..</name> <price>..</price> </item> . . </itemlist> 

At this point, your Java code will look like this:

 final Unmarshaller u = jc.createUnmarshaller(); final File f = new File("D:\\item.xml"); final JAXBElement element = (JAXBElement) u.unmarshal(f); final ItemList itemList = (ItemList) element.getValue(); // This will be helpful if the xml contains more elements for (Item item : itemList.getItems()) { System.out.println(item.getCode()); System.out.println(item.getName()); System.out.println(item.getPrice()); } 
+6
source
 I had the same question, but what if we have xml like below: <itemlist> <item> <code>..</code> <name>..</name> <price>..</price> </item> <item> <code>..</code> <name>..</name> <price>..</price> <item> <code>..</code> <name>..</name> <price>..</price> <item> <code>..</code> <name>..</name> <price>..</price> </item> <item> <code>..</code> <name>..</name> <price>..</price> </item> </item> </item> . . </itemlist> 
-1
source

All Articles