Search This Blog

Wednesday, December 12, 2007

Use Castor for XML Data Binding

This article shows how to convert Java classes to XML and transform that
XML back into Java code, as well as how Castor works and how to design
your classes to function well with the API. The most basic operation in
Castor is to take a Java class and marshal an instance of that class to
XML. You take the class itself and use it as a top-level container element.
You always marshal an instance of a class, not the class itself. A class
is structure, and is best equated to an XML constraint model, like a
DTD or XML Schema. A class on its own has no data, and merely defines
the structure for data to be stored, as well as how it can be accessed.
You instantiate (or obtain from a factory or other instance-producing
mechanism) that class to give it a specific form. Then, you populate the
fields of that instance with actual data. That instance is unique; it
bears the same structure as any other instances of the same class, but
the data is separate. Notice what Castor does not preserve in the XML:
(1) The package of the Java class: a Java package is not part of a class's
structure. It's actually a semantic issue, related to Java namespaces.
So you could unmarshall (convert from XML to Java code) this XML document
to any Book instance that had the same three properties, regardless of
package. (2) Field ordering: order matters in XML, but not in Java
programming. So even though the source file listed the fields in one
order, the XML document used another. That's important in your XML, but
irrelevant in your Book class declaration. (2) Methods: methods, like
a package declaration, have nothing to do with data structuring. So the
XML document doesn't do anything with them; they're ignored. Article
prerequisite: you would do well to have some classes you'd like to
convert to and from XML from a project you're working on. There are
sample classes provided with this and the previous article, but your
own mastery of Castor is best achieved if you apply what you see here
to your own projects.

No comments: