O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.2. Turning XML Documents into Objects

Problem

You need to parse an XML document into an object graph, and you would like to avoid using either the DOM or SAX APIs directly.

Solution

Use the Commons Digester to transform an XML document into an object graph. The Digester allows you to map an XML document structure to an object model in an external XML file containing a set of rules telling the Digester what to do when specific elements are encountered. In this recipe, the following XML document containing a description of a play will be parsed into an object graph:

<?xml version="1.0"?>

<plays>
  <play genre="tragedy" year="1603" language="english">
    <name>Hamlet</name>
    <author>William Shakespeare</author>
    <summary>
      Prince of Denmark freaks out, talks to ghost, gets into a
      crazy nihilistic funk, and dies in a duel.
    </summary>
    <characters>
      <character protagonist="false">
        <name>Claudius</name>
        <description>King of Denmark</description>
      </character>
      <character protagonist="true">
        <name>Hamlet</name>
        <descr>
          Son to the late, and nephew of the present king
        </descr>
      </character>
      <character protagonist="false">
        <name>Horatio</name>
        <descr>
          friend to Hamlet
        </descr>
      </character>
    </characters>
  </play>
</plays>

This XML document contains a list of play elements describing plays by William Shakespeare. One play element describes “Hamlet”; it includes a name, author, and summary element as well as a characters element containing character elements describing characters in the play. After parsing ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required