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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With