Tutorials : Converting XML documents to Java objects with Castor XML :

The way Castor XML works

In order for Castor to convert between XML documents and Java objects, it needs "mapping information" which can be obtained from several sources:

  • through introspection of classes
  • from a mapping file (XML-format)
  • from class descriptors

 The first possibility alone is only an option in simple situations. Normally you'd need to tell Castor how XML-elements and Java-classes should be mapped, and this is done using a mapping file in XML-format.  

Here is a very small example: Assume that you have a class called demo.Person with instance variables called occupation and lastName, and an XML-document containing:

. . . 
<person occupation="programmer">
  <lastname>Gosling</lastname>
</person>
. . . 

A Castor mapping file that will match this document to the Person class is this:  

. . .
<class name="demo.Person">
  <map-to xml="person"/>
  <field name="occupation" type="string">
    <bind-xml name="occupation" node="attribute"/>
  </field>
  <field name="lastName" type="string">
    <bind-xml name="lastname" node="element"/>
  </field>
</class>
. . .

The class- and field-elements refer to the Java class, and the map-to- and bind-xml-elements to the XML-document.  

I won't go into details about how to construct the mapping file--there are several very good articles on the web giving examples on this, and I've listed some of the best in the resources section at the end of the article. Instead we'll start looking at the third mapping option using class descriptors.  

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.