迭代JAXB中的元素 [英] Iterate through the elements in JAXB

查看:79
本文介绍了迭代JAXB中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

我的代码如下:

        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>

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

How can i get all the values displayed? Can anyone help me?

推荐答案

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

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.

所以,你的xml应该以这样的方式出现:

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>

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

这篇关于迭代JAXB中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆