6.2. Turning XML Documents into Objects


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.


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"?>

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

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 ...

Get Jakarta Commons Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.