Developer/Designer Notes

Java Serialize data to XML file

Posted by Kiran Mova on March 20, 2007

Does Java provide facility for XML persistence? The answer is yes. It just seems like Java has hidden this feature in its beans package.

Check this article Serialize Java Data Objects to XML at Java Pro. There is a mention of this at Swing Connection Articles as well.

My scenario. I am developing an web application that operates on a certain data structure. Let us say this structure is “config”. The user can load/save different configs. The config is a simple data structure with a set of ArrayLists and Hashtables. I decided XML is the way to store, since I don’t need to code an format coder/decoder.

Approach 1: Define a new XML format to store my config data. Write code to output data to this XML format and use the SAX parser handlers to import.

Approach 2: Make use of the XMLEncoder and XMLDecoder. (The drawbacks, dependency on the XMLEncoder/XMLDecoder. If the implementation changes in the future versions, the XML files saved with earlier versions will need an upgrade. The XMLEncoder/Decoder are not thread-safe.)

05/02/2007 – Update

After deciding on XMLEncoder/XMLDecoder, things went pretty smooth. Everything worked on my jdk1.6 and netbeans IDE. However for some strange reason, it started to throw up on my – linux jre 1.4.2 version. (I am not sure why the version number of FSF JRE is called 1.4.2, but it is compatible with jdk 1.6, atleast the new for loops works. )

Anyways, XMLEncoder started to throw ClassNotFoundException for the objects that I need to serialize. I found instances of such error on the java forum, where the solution was to set the correct class loader. It didn’t Work.

To my luck, I get to deliver the jre along with my web application, so I got out of this problem easily, but if your application needs to run on a customer’s jre – make sure XMLEncoder can serialize the objects.

If you need alternatives:

Approach 3: Check out XStream

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

 
%d bloggers like this: