If you want a simple way to marshall / unmarshall your pojo -> Xml files, Castor could be very handy. Before reading the docs on the setup and overview and breaking your nerves on it’s rich feature set, lets get going in less than 10 minutes. Castor is extremely powerful but if your purpose is pure marshalling of pojos into xml with namespaces from your xsd, you need to understand -
- 2 method calls (marshal, unmarshall)
- understand how to write a mapping file (pojo to xml)
- the pojo ofcourse
- (optional) xsd file and ofcourse a sample xml file for the xsd
Lets see a basic example with ‘profile’. A profile is a simple pojo which consists of a user profile information (like your facebook profile). It has a Bio Interests, Contact as complex types. Now, create an xsd (optional, you can really skip this step) for the pojo. More often you would prefer to create an xml first and generate the xsd from your favorite tool or you could do vice versa. (I’d recommend using eclipse 3x. Right click and generate!)
Once you figured out the pojo & xml, you have to create a castor mapping file. I’m not going to go in detail on how to create one. The best way I figured out is to read an example mapping file and once you understand, writing your own is a matter of improvising along with a reference guide. Now, the final part – Create a utility class for wrapping up the basic methods of castor along with some exception handling. To make life absolutely easy, I’ve added a main method for testing standalone without a JUnit. Download these 4 files along with castor.jar and you just got a standalone castor example!
Castor xml marshalling/unmarshalling – its that easy!
Post a Comment