vidhya
vidhya

Reputation: 2911

Iterate through the elements in JAXB

I created a method to unmarshall my xml (item.xml) file .But if there are more than one element ,how can i iterate through all the elements and get them displayed?

My Code is as following :

        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 is

       <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 values displayed? Can anyone help me?

Upvotes: 4

Views: 6888

Answers (1)

user278064
user278064

Reputation: 10180

I've used JAXB in some projects at university. As far as I remember, you should return an object, like an ItemList and then query that object in order to retrieve the elements contained.

So, your xml should appear somehow 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 be:

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());
}

Upvotes: 6

Related Questions