Parsing XML using JAXB in Java
Process
Objective is to create Java class files that represent schema from the XML data.
- Create XSD from XML
Generators: http://www.freeformatter.com/xsd-generator.html, http://xmlgrid.net/xml2xsd.html, https://devutilsonline.com/xsd-xml/generate-xsd-from-xml - Use xjc on XSD to create JAXB Java classes
$xjc sample.xsd
Creates a
generated/
folder in the same location as .xsd file
Client code for JAXB Java classes
try { JAXBContext jaxbContext = JAXBContext.newInstance(MyClass.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); StringReader reader = new StringReader("<xml>data</xml>"); MyClass myClassObj = (MyClass) unmarshaller.unmarshal(reader); } catch (JAXBException e) { e.printStackTrace(); }
pom.xml dependencies
<dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.2.7</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.2.7</version> </dependency>
Performance and JAXB Runtime Classes
- You should avoid creating the same
JAXBContext
over and over.JAXBContext
is thread safe and should be reused to improve performance. Marshaller
/Unmarshaller
are not thread safe, but are quick to create. It’s not as big a deal to reuse them.
Notes
- xjc comes with JDK
References
- http://www.oracle.com/technetwork/articles/javase/index-140168.html
- http://www.journaldev.com/1234/jaxb-example-tutorial
- http://stackoverflow.com/questions/18607318/how-can-i-improve-jaxb-performance