如何通过Java中的声明类型来解释Jaxb到Unmarshal?

时间:2017-03-17 07:32:44

标签: java xml jaxb unmarshalling

我试图在JAVA中使用JAXB解组一个简单的xml文档:

<?xml version="1.0" encoding="UTF-8"?>
  <root>
    <fruit>banana</fruit>
    <fruit>apple</fruit>
    <vegetable>tomatoe</vegetable>
    <vegetable>potatoe</vegetable>
    <fruit>pineaple</fruit>
    <vegetable>cabbage</vegetable>
    <vegetable>carrot</vegetable>
    <fruit>strawberry</fruit>
  </root>

我无法理解工作方法

unmarshal <T> JAXBElement<T> unmarshal(Node node,Class<T> declaredType) throws JAXBException

因为对于我的问题,我必须使用JAXB和解组来代表所有“root”子项。 我需要将这个xml解组为java对象。

先前感谢您支付我的问题的时间。

1 个答案:

答案 0 :(得分:0)

只需从根元素中解组:

JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
Unmarshaller unmarhsaller = jaxbContext.createUnmarshaller();
Root root = (Root) unmarhsaller.unmarshal(new File("file.xml"));

//getting a list of fruit nodes (suppose you have created XML document object model)
List<Fruit> fruit = root.getFruit();
// do your stuff here
相关问题