Developing data-binding for Address Book

We define the address book as holding a collection of persons. To build this, we will have to create a mapping for the data-binding framework, and we will see how it will be able to set up a java.util.Collection of Persons. We will also learn about mapping attributes (as in <foo anAttribute="somevalue">).

Here are the steps we will follow:

Create an XML representation of the address book

Create a Java object representing the address book

Create a mapping.xml file to allow Castor XML to marshal and unmarshal

Use Castor XML to display the address book

Step One: Create an XML representation of the address book

Our address book will have an <addressbook> tag wrapping around the <person> elements that we defined earlier:

Now we have the programming interface that we'll use to work with an address book, and we have defined the XML representation. We need to tie these together, and that is where the mapping file comes in.

Looking at the mapping file, you will see that it is built from the point of view of the Java class. We have Person.java and Addressbook.java, and both have a <class> element to describe them.

Each <class> has fields. This is where we tell Castor the name of the fields, their type, if they are an element or an attribute, and if there is one of them or a collection.

The following snippet describes the fact that the given tag has an attribute, of type String, with the name name. From this, Castor knows that the XML document will hold <addressbook name="the value">.

The only real difference here is that we are no longer using the static Unmarshaller.unmarshal() method. Now we instantiate an Unmarshaller object, and set the mapping to the newly created Mapping() object. The Mapping() object loads the XML mapping file that we just created:

Conclusion

We have shown that working with XML doesn't mean that you have to delve into the books to learn SAX, DOM, JAXP, and all the other TLAs. Castor's XML data-binding provides a simple but powerful mechanism to work with XML and Java objects.