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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access