Java XML data binding with Castor

In working on an XML data feed project at work I needed to generate the feed from our POJO domain model. I was pleasantly surprised to find that Castor XML made this task quite easy.

The Marshalling framework will marshall a bean to XML as follows:

MyBean myBean = new MyBean();
myBean.setId(new Integer(12));
myBean.setName("foo");
myBean.setDescription("bar");
Marshaller.marshal(myBean, doc.getDocumentElement());

which creates XML that looks something like this:


<myfeed>
    <mybean>
        <id>12</id>
        <name>foo</name>
        <description>bar</description>
    </mybean>
</myfeed>

You also have the option to create your own mapping file to give you some control over the format of the generated XML. I opted to use an XSLT to beautify the feed rather than using the Castor Mapping. I figured if other developers work on this project in the future chances of them knowing XSLT are good whereas chances of them knowing Castor's XML mapping file format would be slim.

The biggest drawback of this approach of auto generating XML from your domain model is that it is very brittle. One change to the domain model and the generated feed is different and then customers come complaining. I opted to use a DTD (or XSD) and then validate a mini version of the feed in a unit test. That way if a developer makes a change to the domain model causing the feed to change, the continuous integration system will let us know there was a problem when the unit test fails.

This entry was posted in Java. Bookmark the permalink.