Jaxb如何在Java中通过声明类型解组?
问题描述:
我曾试图用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对象。
以前感谢您为我的问题花费的时间。
答
对于从根元素只是解编:
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