2017-03-17 34 views
0

我曾試圖用JAVA JAXB解組一個簡單的XML文檔:Jaxb如何在Java中通過聲明類型解組?

<?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的孩子和unmarshaling。 我需要將這個xml解組爲java對象。

以前感謝您爲我的問題花費的時間。

回答

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