迭代JAXB中的元素

时间:2012-06-22 08:45:57

标签: java

我创建了一个解组我的xml(item.xml)文件的方法。但是如果有多个元素,我如何遍历所有元素并显示它们?

我的代码如下:

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

如果我的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>

如何显示所有值?任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:6)

我在大学的一些项目中使用过JAXB。 据我所知,你应该返回一个对象,比如ItemList,然后查询该对象以便检索包含的元素。

所以,你的xml应该以某种方式出现:

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

此时, Java 代码将为:

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