Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JaxB automatic parsing from XML to Java classes

I am new about jaxb. My question is the following: using jaxb, is it possible to do automatic mapping from an xml file to a java object? Starting from xml file, is there something generate the Java class with annotations jaxb relaitve?

like image 254
Gaetano Tortora Avatar asked May 06 '13 10:05

Gaetano Tortora


1 Answers

It is indeed possible. However, you'll need an XSD rather than an XML file. There are tools out there (Trang, for instance) that can infer an XSD from one or more example XML files.

Take into account that generating this XSD with a tool might get you inaccurate results if the XML sample isn't complete, or if the schema can't be fully represented in a single XML file (exclusive elements, etc).

Once you have an XSD, use xjc in order to generate the marshaller/unmarshaller classes.

xjc myxsd.xsd

This will generate the annotated classes that JAXB will use for marshalling/unmarshalling. Notice you could also have coded these classes yourself. Once you have them, just use them in your code:

File file = new File("myFile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(MyRootElement.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
MyRootElement element = (MyRootElement) jaxbUnmarshaller.unmarshal(file);
like image 166
Xavi López Avatar answered Nov 02 '22 06:11

Xavi López