Jakarta Commons – Digester component

In: Java

28 May 2003

The Digester component of the Jakarta Commons project is an extremely useful and well-designed package that allows you to parse XML files at a higher level of abstraction in Java. This allows developers to concentrate on processing XML rather than get unnecessarily involved in parsing functions. With Digester, you can use simple matching patterns and write corresponding callback functions which are called whenever a match is found. For example, consider the XML snippet below.

<book>
  <title>The Hobbit</title>
  <author>J. R. R. Tolkien</author>
</book>

In Digester, you can write this (in Java):

Digester digester = new Digester();

digester.addObjectCreate("book", "Book");
digester.addCallMethod("book/title","setTitle",0);
digester.addCallMethod("book/authors","setAuthor", 0);

digester.parse("books.xml");

When Digester parses the XML file (assumed to be “books.xml”), it will create a Book object when it encounters the tag, and it will call the setTitle() and setAuthor() methods with the arguments “The Hobbit” and “J. R. R. Tolkien” respectively upon encountering the <title> and <author> tags. Isn’t this very intuitive? I think it’s a very clean abstraction layer on top of XML parsing that allows developers to get on with “real” development work. Once again the Jakarta Project amazes me with what it can do.

Comments are closed.