Serializing Java Objects as XML
Reading Archived Objects
Reading (unarchiving) a Java object from an XML archive is just as easy as reading it from a serialized object binary file. However, instead of using java.io.ObjectInputStream, you use java.beans.XMLDecoder. Here is the algorithm:
// Create input stream. FileInputStream fos = new FileInputStream("foo.xml"); // Create XML decoder. XMLDecoder xdec = new XMLDecoder(fis); // Read object. Foo aFoo = (Foo) xdec.readObject();
ReadXML demonstrates the above algorithm. It is a simple program that unarchives an object from an XML archive created by WriteQuarkXML.
Object Graphs
XMLEncoder is designed to archive graphs of objects. This means that if an object has properties that reference other objects, those objects also will be archived. Note, though, that XMLEncoder will only traverse properties that are exposed via the JavaBean naming conventions (such as setX or getX) or a BeanInfo class.
WriteAtomXML is a program that demonstrates archiving an object graph. It archives an instance of Atom that references two instances of Quark. ReadXML can be used to read the archive that WriteAtomXML creates.
Resources
- Example Programs -- examples.zip
- Using XMLEncoder -- http://java.sun.com/products/jfc/tsc/articles/persistence4/index.html
- Long-Term Persistence for JavaBeans -- http://java.sun.com/products/jfc/tsc/articles/persistence/index.html
- Long-Term Persistence of JavaBeans Components: XML Schema -- http://java.sun.com/products/jfc/tsc/articles/persistence3/index.html
- XML Archive DTD -- http://java.sun.com/products/jfc/tsc/articles/persistence3/javabeans.dtd
About the Author
Thornton Rose is a contract software developer in Atlanta, Ga. He can be reached via e-mail at thornton.rose@mindspring.com.
Copyright© 2002, Thornton Rose.
