Monday, 21 September 2015

JAXB - XML to Java in 2 lines of Code!

A couple of weeks ago I was presented with a bunch of xml files for which I was also given the xsd document.  The task was to calculate some metrics based on properties of the xml files.

Not too complicated.  All I had to do was:

  1. Convert the xml files to Java objects.
  2. Write some code to perform a calculation on said objects.
I hadn't actually tried this before but I challenged myself to do this (at least the boilerplate of point 1) in 2 lines of code. Here's how I did it:

Step 1 - Create a Java data model

I created a project in IntelliJ and dropped my xsd document in a resources directory.

I then highlighted the xsd file and clicked Tools->JAXB->Generate Java Code

I was presented with a dialogue box as below

Click OK and hey presto your whole data model has been created into Java objects.

Step 2 - Deserialise the xml file into Java Objects  

//line 1 create an Unmarshaller for the object type you are reading from the xml file
Unmarshaller um = JAXBContext.newInstance(DataObject.class).createUnmarshaller();
//line 2 deserialise the xml file into a java object
DataObject dataOject = (DataObject)um.unmarshal(new FileReader("DataObject.xml"));
//now run the calculation on dataObject

So that's it - only took 2 lines!

No comments:

Post a Comment