Hello friends! How’s it going?
Has the following ever happened to you? You show up to work one morning and your boss tells you, “I need you to take this data and turn it into XML.” Well, this has happened to me, and in this blog post I’m going to show you how to do this quickly.
In all fairness to my boss, he did give me an XSD file describing the structure of the XML I was asked to generate. But what is an XSD file anyway?
XSD stands for XML Schema Definition. It’s nothing but another XML file of a known and canonical format which is used to describe the structure of another XML file. For example, if I want to dump an employee’s data into an XML, the XSD’s job is to let everyone know that an employee must have a name, an address, a social security number, that he can hold several positions in the same organization and so forth… But most importantly, it describes the layout of all that data in the XML file.
Here’s a sample XSD example for your reference describing an employees XML:
But, who cares? What’s the use of an XSD file? Well, for starters, your IDE probably uses XSD files to validate that the XML files you write are valid (this is true for example when working with Spring, Hibernate, and of course Mule ESB). But it could also be used for automatic mapping and code generation. What JAXB does is to read the XSD file to automatically generate a set of classes that mimic the structure of the XML and that allows for storing the same data in the same way. Once those classes exists, it’s easy for JAXB to marshall XML data into those objects and vice versa.
JAXB has a terminal command that takes an XSD file and turns it into a Java Bean. This command is called XJC and is present on the bin/ folder of any JDK installation since version 1.6. Here’s a sample of how to use it:
The command above will create a java class with the proper JAXB annotations to perform XML marshalling and unmarshalling. It will also create a second class called ObjectFactory, which it will use internally when performing the transformations. You need to add these classes into your project. For simplicity let’s assume that you put them in the package com.mulesoft.example.
Then it’s just a matter of populating the bean and using Mule’s JAXB Transformers to generate the XML. Sample code looks as follows:
That’s it. You just made your boss happy. Do you really want to impress him though? Let’s also see how you can do the reverse operation and transform an XML file into a Java Object.
Mule already provides an object-to-xml-transformer out of the box and it would work just fine in this case, but just for the sake of completeness, let’s see how you can do the same thing using JAX
And that’s it! You’re all set! Now show it to your boss and get him to buy you beer!