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!


5 comments:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete
  2. Hi, I am a big follower of your blog. Really very informative post you shared here. Keep sharing this type of informative blog. Waiting for your next update. If anyone wants to become a Java professional learn Java Training in Bangalore. Nowadays Java has tons of job opportunities for all professionals.

    ReplyDelete
  3. In these blog very impressed to me.I'm many time following your blog it's really good article post.All Company using their java programming language many job opening in IT industries.If you want to be any learn for java coding knowledge visit us Java Training in Chennai
    Selenium Training in Chennai

    ReplyDelete
  4. Thank you for taking the time to provide us with your valuable information..CCNA Training Institute in Chennai | CCNA Training Institute in Velachery.

    ReplyDelete