HOWTO Serialize Objects To and From XML

Serialization is the conversion of an object to a data stream for the purpose of portability. POJava Persistence provides two utility objects for serialization by converting objects to XML and back. While serialization to a binary format is useful, serialization to a document provides an even more portable medium, one that can be easily stored in a String, a varchar in a database table, or imbedded in another XML document.

This HOWTO document will demonstrate the use of the org.pojava.persistence.serial classes XmlParser and XmlSerializer to convert objects to and from XML.

XmlSerializer

The XmlSerializer is designed to serialize POJO's to XML with almost no coding or configuration effort. Typical usage looks like this:

MyPojo pojo=new MyPojo();
XmlSerializer serializer=new XmlSerializer();
String document=serializer.toXml(pojo);

XmlParser

The parser is the reverse of the serializer, converting an XML document back to Object form. If the document was generated from XmlSerializer, it is equally simple to use. The parser returns your object as type "Object", so you'll usually cast it in your call to the parser.
XmlParser parser=new XmlParser();
MoPojo newPojo=(MyPojo) parser.parse(document);

What is a POJO?

A POJO is a "plain old java object". Conceptually, if you start with a new empty class, define some private properties with camel-cased names consisting of primitives, their object equivalents, and other POJO's, and let your code editor auto-generate getters and setters, then you have a POJO.

POJava uses reflection to determine the public getters and setters of a class (also known as accessors and mutators) and generates XML that matches property names to tag names where available, and uses the name "obj" on tags where a name is unavailable. Where a type is not inherent in the property itself, such as an object stored within a property whose type is Object or List, then an attribute is added within the XML to specify the class of the object stored.

POJava's serializer detects multiple references to the same object, and will restore those relationships when deserializing.