Code I/O

A topnotch WordPress.com site

5 Minutes on Java – Playing with XML and Java

Leave a comment

Marshelling/unmarshelling of XML is very common.  JAXB and XStream come to my mind when ever I need to work with XML and Java.

Recently I had an interesting conversation with my colleague, he preferred JAXB over others for the following reasons

  • He wanted to use something that is as good as intrinsic of the language.
  • He did not mind the over head of using annotations.
  • nor did he want the dependency on a vendor or get into sustainability issues.

After having thought for a while, I realized software and bugs go hand in hand.  When it comes to delivering projects on schedule, reducing the coding time/complexity is good.  Thirdly, when a vendor has already done a good job of validating the concepts, why not use it in the given constraints.

XStream is equally powerful, in my experience (perhaps I’ve over simplified it), but for the purposes of the tasks I’ve used it for, it has really proven its metal.

The selling points from my point of view is:

  • I really don’t have to care about the XML schema/schema generation tools to work with.
  • When POJO’s are involved, I can marshall/unmarshall it as XML document using a single API call.
  • Once the Java objects are constructed, it can used as ever before.

Everything is good, except for the sustainability part, however, knowing the way Java has touched the lives of billions, sustainability is not a concern as of today.  Perhaps there is more of a organizational standard that forbids you from using XStream.

Check out the tutorial from http://xstream.codehaus.org/tutorial.html

Here is how I’ve used it to convert an XML stream to a Java object

@POST
@Consumes ("application/xml")
@Produces ("application/xml")
public Response postHandler(InputStream input){
String object = input.toString();

URI uri = uriInfo.getAbsolutePathBuilder().path(object).build();
logger.debug("Received Object: " + object);

StringBuffer buff = new StringBuffer();

XStream xstream = new XStream(new DomDriver());
xstream.alias("data", MyData.class);

MyData data = (MyData) xstream.fromXML(input);

...

...

}

Now sending a XML stream to user is as simple as creating it.

class MyData {

String toXML(){

XStream xstream = new XStream(new DomDriver());
xstream.alias("data", MyData.class);

return xstream.toXML(this);

}

}

Learning: if something can be done in few steps, let’s do in just those few steps 🙂

If there is something that you feel is better, please let me know.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s