Armer B.
Armer B.

Reputation: 772

How work Jaxb to Unmarshal by Declared Type in Java?

I have tried to unmarshal one simple xml document with JAXB in 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>

I can't understand how work method

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

because for my issue I have to represent all "root" children with JAXB and unmarshaling. I need to unmarshal this xml to java object.

Thanks previously for the time spend for my issue.

Upvotes: 1

Views: 553

Answers (1)

Vitaliy
Vitaliy

Reputation: 489

For unmarshaling from the root element just:

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

Upvotes: 1

Related Questions