Gaetano Tortora
Gaetano Tortora

Reputation: 105

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?

Upvotes: 5

Views: 5090

Answers (2)

Xavi López
Xavi López

Reputation: 27880

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);

Upvotes: 6

Vineet Singla
Vineet Singla

Reputation: 1677

Yes, JAXB automatically does marshalling and unmarshalling but it requires a schema file. JaxB is used to bind XML with Java objects. Using the XSD schema file, it does marshalling and unmarshalling. There are few simple ant tasks like XJC that can be used.

Upvotes: 1

Related Questions