Parsing XML using JAXB in Java

Process

Objective is to create Java class files that represent schema from the XML data.

 

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

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *