ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Learning and Using Jakarta Digester
Pages: 1, 2, 3

Specifying Patterns and Rules

The Digester class processes the input XML document based on patterns and rules. The patterns must match XML elements, based on their name and location in the document tree. The syntax used to describe the matching patterns resembles the XPath match patterns, a little: the pattern catalog matches the top-level <catalog> element, the pattern catalog/book matches a <book> element nested directly inside a <catalog> element, but nowhere else in the document, etc.



All patterns are absolute: the entire path from the root element on down has to be specified. The only exception are patterns containing the wildcard operator *: the pattern */name will match a <name> element anywhere in the document. Also note that there is no need for a special designation for the root element, since all paths are absolute.

Related Reading

Java & XML Data Binding
By Brett McLaughlin

Whenever the Digester encounters one of the specified patterns, it performs the actions that have been associated with it. In this, the Digester framework is of course related to a SAX parser (and in fact, the Digester class implements org.xml.sax.ContentHandler and maintains the parse stack). All rules to be used with the Digester must extend org.apache.commons.digester.Rule -- which in itself exposes methods similar to the SAX ContentHandler callbacks: begin() and end() are called when the opening and closing tags of the matched element are encountered.

The body() method is called for the content nested inside of the matched element, and finally, there is a finish() method, which is called once processing of the closing tag is complete, to provide a hook to do possible final clean-up chores. Most application developers will not have to concern themselves with these functions, however, since the standard rules that ship with the framework are likely to provide all desired functionality.

To unmarshal a document, then, create an instance of the org.apache.commons.digester.Digester class, configure it if necessary, specify the required patterns and rules, and finally, pass a reference to the XML file to the parse() method. This is demonstrated in the DigesterDriver class below. (The filename of the input XML document must be specified on the command line.)

import org.apache.commons.digester.*;

import java.io.*;
import java.util.*;

public class DigesterDriver {

   public static void main( String[] args ) {

      try {
         Digester digester = new Digester();
         digester.setValidating( false );

         digester.addObjectCreate( "catalog", Catalog.class );

         digester.addObjectCreate( "catalog/book", Book.class );
         digester.addBeanPropertySetter( "catalog/book/author", "author" );
         digester.addBeanPropertySetter( "catalog/book/title", "title" );
         digester.addSetNext( "catalog/book", "addBook" );

         digester.addObjectCreate( "catalog/magazine", Magazine.class );
         digester.addBeanPropertySetter( "catalog/magazine/name", "name" );

         digester.addObjectCreate( "catalog/magazine/article", Article.class );
         digester.addSetProperties( "catalog/magazine/article", "page", "page" );
         digester.addBeanPropertySetter( "catalog/magazine/article/headline" ); 
         digester.addSetNext( "catalog/magazine/article", "addArticle" );

         digester.addSetNext( "catalog/magazine", "addMagazine" );

         File input = new File( args[0] );
         Catalog c = (Catalog)digester.parse( input );

         System.out.println( c.toString() );

      } catch( Exception exc ) {
         exc.printStackTrace();
      }
   }
}

After instantiating the Digester, we specify that it should not validate the XML document against a DTD -- because we did not define one for our simple Catalog document. Then we specify the patterns and the associated rules: the ObjectCreateRule creates an instance of the specified class and pushes it onto the parse stack. The SetPropertiesRule sets a bean property to the value of an XML attribute of the current element -- the first argument to the rule is the name of the attribute, the second, the name of the property.

Whereas SetPropertiesRule takes the value from an attribute, BeanPropertySetterRule takes the value from the raw character data nested inside of the current element. It is not necessary to specify the name of the property to set when using BeanPropertySetterRule: it defaults to the name of the current XML element. In the example above, this default is being used in the rule definition matching the catalog/magazine/article/headline pattern. Finally, the SetNextRule pops the object on top of the parse stack and passes it to the named method on the object below it -- it is commonly used to insert a finished bean into its parent.

Note that it is possible to register several rules for the same pattern. If this occurs, the rules are executed in the order in which they are added to the Digester -- for instance, to deal with the <article> element, found at catalog/magazine/article, we first create the appropriate article bean, then set the page property, and finally pop the completed article bean and insert it into its magazine parent.

Invoking Arbitrary Functions

It is not only possible to set bean properties, but to invoke arbitrary methods on objects in the stack. This is accomplished using the CallMethodRule to specify the method name and, optionally, the number and type of arguments passed to it. Subsequent specifications of the CallParamRule define the parameter values to be passed to the invoked functions. The values can be taken either from named attributes of the current XML element, or from the raw character data contained by the current element. For instance, rather than using the BeanPropertySetterRule in the DigesterDriver implementation above, we could have achieved the same effect by calling the property setter explicitly, and passing the data as parameter:

   digester.addCallMethod( "catalog/book/author", "setAuthor", 1 );
   digester.addCallParam( "catalog/book/author", 0 );

The first line gives the name of the method to call (setAuthor()), and the expected number of parameters (1). The second line says to take the value of the function parameter from the character data contained in the <author> element and pass it as first element in the array of arguments (i.e., the array element with index 0). Had we also specified an attribute name (e.g., digester.addCallParam( "catalog/book/author", 0, "author" );), the value would have been taken from the respective attribute of the current element instead.

One important caveat: confusingly, digester.addCallMethod( "pattern", "methodName", 0 ); does not specify a call to a method taking no arguments -- instead, it specifies a call to a method taking one argument, the value of which is taken from the character data of the current XML element! We therefore have yet another way to implement a replacement for BeanPropertySetterRule:

   digester.addCallMethod( "catalog/book/author", "setAuthor", 0 );

To call a method that truly takes no parameters, use digester.addCallMethod( "pattern", "methodName" );.

Pages: 1, 2, 3

Next Pagearrow