Basic XML Unmarshalling in Java

I frequently find myself groaning in agony over having to deal with more XML coming in to my various Java applications. I thought I would finally do something about it, so I wrote the code below. It is very simple, but performs the way I need it to. Basically, you give it a class that specifies the properties from the XML. Each field is annotated with the name that it correlates to in the XML string. Below is the code, and below that is an example.

The other class is a class that a user must provide. My test class is the following:

A sample execution would then be:

The output of this then becomes:

name: name 1, low: 76, high: 77
name: name 2, low: 1, high: 2
name: name 3, low: 3, high: 42

The reason why the output is above is because I have overridden the toString() method, but of course all of the fields are accessible just like any other publically accessible field.

Basic I know, but it is reusable, and I plan to make use of this code in the future to stop me having to groan in agony over dealing with XML text.

8 thoughts on “Basic XML Unmarshalling in Java”

  1. Yes, it does, but as I noted, it is a simple implementation for a specific circumstance, and in that instance having to use something more complex is overkill. XStream binary packages are nearly 8mb, which is overkill for when the only need is to quickly and easily interpret a string of xml, as was my use case.

  2. JAX-B either schemagen to make a schema out of models and then its a one line thing to unmarshel into models is a lot easier imo method. Plus the latest version comes shipped in the current JDK.

  3. James, thanks for the comment about dom4j. I’m always loath to include new libraries (especially given the number of xml libraries!), but I’m always happy to hear recommendations. I too have used xpath queries to pull out specific values, and that is a good approach for a more complex xml structure, but I still like the above code for simple use cases.

    Kevin, unfortunately it looks like wordpress removed some of your xml syntax there, so I can’t give a proper answer. Regardless, my use case is a very simple one, and the implementation above is only enough to meet that use case. I have not tested it on more difficult scenarios, although I’m sure the code could be improved to handle them.

Leave a Reply