<?xml version="1.0" encoding="ISO-8859-1"?>
<!--DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN" 
              "http://www.oasis-open.org/docbook/xml/4.0/docbookx.dtd"-->
<!--
     Copyright 2002 (C) MetaStuff, Ltd. All Rights Reserved.
     This software is open source. 
 
   Redistribution and use of this software and associated documentation
   ("Software"), with or without modification, are permitted provided
   that the following conditions are met:
  
   1. Redistributions of source code must retain copyright
      copy of this document.
  
   2. Redistributions in binary form must reproduce the
      above copyright notice, this list of conditions and the
      following disclaimer in the documentation and/or other
      materials provided with the distribution.
  
   3. The name "DOM4J" must not be used to endorse or promote
      products derived from this Software without prior written
      permission of MetaStuff, Ltd.  For written permission,
      please contact dom4j-info@metastuff.com.
  
   4. Products derived from this Software may not be called "DOM4J"
      nor may "DOM4J" appear in their names without prior written
      permission of MetaStuff, Ltd. DOM4J is a registered
      trademark of MetaStuff, Ltd.
  
   5. Due credit should be given to the DOM4J Project - 
      http://www.dom4j.org
  
   THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
   NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
   METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
   STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   OF THE POSSIBILITY OF SUCH DAMAGE.
  
   Copyright 2002 (C) MetaStuff, Ltd. All Rights Reserved.
  
   $Id: cookbook.xml,v 1.5 2004/08/17 18:24:26 maartenc Exp $ 
-->

<book>
<bookinfo>
<title>dom4j cookbook</title>
<authorgroup>
  <author><honorific>Mr</honorific><firstname>Tobias</firstname><surname>Rademacher</surname></author>
  <author><honorific>Mr</honorific><firstname>James</firstname><surname>Strachan</surname></author>
</authorgroup>
<revhistory>
    <revision>
      <revnumber>0.1.0</revnumber>
      <date>02-05-09</date>
      <authorinitials>tradem</authorinitials>
      <revdescription>
        <itemizedlist>
            <listitem><para>Fixed typos</para></listitem>
            <listitem><para>Better understable description of some situations</para></listitem>
            <listitem><para>Use of programlistingco for rule API</para></listitem>           
        </itemizedlist>
      </revdescription>
    </revision>
    <revision>
      <revnumber>0.0.9</revnumber>
      <date>02-05-01</date>
      <authorinitials>tradem</authorinitials>
      <revdescription>
        <itemizedlist>
            <listitem><para>Added rule API description &amp; samples</para></listitem>
            <listitem><para>Added JRV API sample to schemata chapter</para></listitem>
            <listitem><para>Used width constrains for programlistings</para></listitem>           
	    <listitem><para>Extented XPath samples</para></listitem>
      </itemizedlist>
      </revdescription>
  </revision>
  <revision>
      <revnumber>0.0.8</revnumber>
      <date>01-09-25</date>
      <authorinitials>tradem</authorinitials>
      <revdescription>
         <para>Fixed the MSV sample in order make it compilable. Lot's of thanks to Martijn Koster for pointing that out.</para>
      </revdescription>
  </revision>
 <revision>
    <revnumber>0.0.7</revnumber>
    <date>01-09-03</date>
    <authorinitials>tradem</authorinitials>
    <revdescription>
      <itemizedlist>
        <listitem><para>Completed the Schema chapter.</para></listitem>
        <listitem><para>Fixed the XPath sample.</para></listitem>
      </itemizedlist>
    </revdescription>
  </revision>
  <revision>
    <revnumber>0.0.6</revnumber>
    <date>01-08-03</date>
    <authorinitials>jstrachan</authorinitials>
    <revdescription>
      <itemizedlist>
        <listitem><para>Fixed a few typos and corrected the odd bit of grammar and code.</para></listitem>
      </itemizedlist>
    </revdescription>
  </revision>
  <revision>
    <revnumber>0.0.5</revnumber>
    <date>01-07-09</date>
    <authorinitials>tradem</authorinitials>
    <revdescription>
      <itemizedlist>
        <listitem><para>Fixing xml structure mistake</para></listitem>
        <listitem><para>Make Writer samples dom4j 0.6 compliant</para></listitem>
      </itemizedlist>
    </revdescription>
  </revision>
<revision>
    <revnumber>0.0.4</revnumber>
    <date>01-07-06</date>
    <authorinitials>tradem</authorinitials>
    <revdescription>
      <itemizedlist>
        <listitem><para>Fixing spelling/gramma mistakes</para></listitem>
        <listitem><para>Complete vistor listing</para></listitem>
      </itemizedlist>
    </revdescription>
</revision>
<revision>
  <revnumber>0.0.3</revnumber>
  <date>01-06-20</date>
  <authorinitials>tradem</authorinitials>
  <revdescription>
    <para>Completed doc for alpha release</para>
  </revdescription>
</revision>
<revision>
  <revnumber>0.0.2</revnumber>
  <date>01-06-06</date>
  <authorinitials>tradem</authorinitials>
  <revdescription>
    <para>Added "Secret of DocumentBuilder" and "Serialization"</para>
  </revdescription>
</revision>
<revision>
  <revnumber>0.0.1</revnumber>
  <date>01-06-02</date>
  <authorinitials>tradem</authorinitials>
  <revdescription>
    <para>Created the document</para>
  </revdescription>
  </revision>
</revhistory>
<pubdate>September 2001</pubdate>
<abstract>
  <para>This document provides a practical introduction to dom4j. It guides you through by using a lot of examples and is based on dom4j v1.0</para>
</abstract>
</bookinfo>
<preface>
  <title>Foreword</title>
<para>
</para>
</preface>
<chapter>
<title>Introducing dom4j</title>
<para>
<application>dom4j</application> is a object model representing an XML Tree in memory.
<application>dom4j</application> offers a easy-to-use API that provides a powerful set of
features to process, manipulate or navigate XML and work with XPath and XSLT as well as integrate with SAX, JAXP and DOM.
</para>
<para>
<application>dom4j</application> is designed to be interface-based in order to provide highly configurable implementation strategies.
You are able to create your own XML tree implementations by simply providing a DocumentFactory implementation.
This makes it very simple to reuse much of the dom4j code while extending it to provide whatever implementation features you wish.
</para>
<para>
This
document will guide you through <application>dom4j</application>'s features in a practical way
using a lot of examples with source code. The document is
also designed as a reference so that you don't have to read the entire document at once. This guide concentrates on daily work with
<application>dom4j</application> and is therefore called <emphasis>cookbook</emphasis>.
</para>
</chapter>
<chapter>
<title>Creation of an XML Object Model using dom4j</title>
<para>
Normally all starts with a set of xml-files or a single xml file that you want to process, manipulate or navigate through to extract some
values necessary in your application. Most Java Open-Source projects using XML for deployment or as a replacement for property files in order
to get easily readable property data.
</para>

<section><title>Reading XML data</title>
<para>
How does <application>dom4j</application> help you to get at the data stored in XML?
<application>dom4j</application> comes with a set of
builder classes that parse the xml data and create
a tree-like object structure in memory.
You can easily manipulate and navigate through that model.
The following example shows how you can
read your data using <application>dom4j</application> API.

<programlisting width="59">
import java.io.File;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class DeployFileLoaderSample {

  /** dom4j object model representation of a xml document. Note: We use the interface(!) not its implementation */
  private Document doc;

  /**
   * Loads a document from a file.
   *
   * @throw a org.dom4j.DocumentException occurs whenever the buildprocess fails.
   */
  public void parseWithSAX(File aFile) throws DocumentException {
    SAXReader xmlReader = new SAXReader();
    this.doc = xmlReader.read(aFile);
  }
}
</programlisting>

</para>

<para>
The above example code should clarify the use of <classname>org.dom4j.io.SAXReader</classname> to
build a complete <application>dom4j</application> tree from a given file.
The org.dom4j.io package contains a set of classes
for creation and serialization of <acronym>XML</acronym> objects.
The read() method
is overloaded so that you able to pass different kind of object that represents a source.
</para>

<itemizedlist>
  <listitem><para><classname>java.lang.String</classname> - a SystemId is a String that contains a URI e.g. a URL to a XML file</para></listitem>
  <listitem><para><classname>java.net.URL</classname> - represents a Uniform Resource Loader or a Uniform Resource Identifier. Encapsulates a URL.</para></listitem>
  <listitem><para><classname>java.io.InputStream</classname> - an open input stream that transports xml data</para></listitem>
  <listitem><para><classname>java.io.Reader</classname> - more compatible. Has abilitiy to specify encoding scheme</para></listitem>
  <listitem><para><classname>org.sax.InputSource</classname> - a single input source for a <acronym>XML</acronym> entity.</para></listitem>
</itemizedlist>

<para>
Lets add more more flexibility to our <classname>DeployFileLoaderSample</classname> by adding new methods.
</para>

<programlisting width="59">
import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class DeployFileLoaderSample {

  /** dom4j object model representation of a xml document. Note: We use the interface(!) not its implementation */
  private Document doc;

  /**
   * Loads a document from a file.
   *
   * @param aFile the data source
   * @throw a org.dom4j.DocumentExcepiton occurs on parsing failure.
   */
  public void parseWithSAX(File aFile) throws DocumentException {
    SAXReader xmlReader = new SAXReader();
    this.doc = xmlReader.read(aFile);
  }

  /**
   * Loads a document from a file.
   *
   * @param aURL the data source
   * @throw a org.dom4j.DocumentExcepiton occurs on parsing failure.
   */
  public void parseWithSAX(URL aURL) throws DocumentException {
    SAXReader xmlReader = new SAXReader();
    this.doc = xmlReader.read(aURL);
  }


}
</programlisting>

</section>

<section>
<title>Integrating with other XML APIs</title>
<para>
<application>dom4j</application> also offers classes for integration with
the two original XML processing APIs - SAX and DOM.
So far we have been talking about reading a document with SAX.
The <classname>org.dom4j.SAXContentHandler</classname> class implements several
SAX interfaces directly (such as ContentHandler) so that you can embed <application>dom4j</application>
directly inside any SAX application.
You can also use this class to implement your own specific SAX-based Reader class if you need to.
</para>

<para>
The <classname>DOMReader</classname> class allows you to convert an existing <acronym>DOM</acronym> tree
into a <application>dom4j</application> tree.
This could be useful if you already used DOM and want to replace it step by step
with <application>dom4j</application> or if you just needs some of <acronym>DOM</acronym>'s
behavior and want to save memory resources by transforming it in a <application>dom4j</application> Model.
You are able to transform a DOM Document, a <acronym>DOM</acronym> node branch and a single element.
</para>

<programlisting width="59">
import org.sax.Document;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.DOMReader;

public class DOMIntegratorSample {

  /** converts a W3C DOM document into a dom4j document */
  public Document buildDocment(org.w3c.dom.Document domDocument) {
    DOMReader xmlReader = new DOMReader();
    return xmlReader.read(domDocument);
  }
}

</programlisting>
</section>

<section><title>The secret of DocumentFactory</title>
We have talked a lot of reading existing XML information e.g. from files, URL's or even Streams.
Sometimes it's necessary to generate a XML document programmatically.
The class <classname>org.dom4j.DocumentFactory</classname> defines a set of factory methods to create documents, document
types, elements, attributes, unparsed character data (CDATA), a namespace, an <acronym>XPath</acronym> object, a NodeFilter and
some other useful instances. This makes the <classname>DocumentFactory</classname> a central class whenever you have to create
one of these instances by yourself.
</section>

<programlisting width="59">

import org.dom4j.DocumentFactory;
import org.dom4j.Document;
import org.dom4j.Element;

public class DeployFileCreator {

  private DocumentFactory factory = DocumentFactory.getInstance();
  private Document doc;

  public void generateDoc(String aRootElement) {
    doc = DocumentFactory.getInstance().createDocument();
    Element root = doc.addElement(aRootElement);
  }

}

</programlisting>

<para>
The listing shows how to generate a new Document from scratch.
The method <classname>generateDoc(String aRootElement)</classname> takes a String parameter.
The string value contains the name of the root element of the new document.
As you can see <classname>org.dom4j.DocumentFactory</classname> is a singleton
accessible via <classname>getInstance()</classname>.

The <classname>DocumentFactory</classname> methods follow the <emphasis>createXXX()</emphasis> naming convention.
For example, if you want to create a Attribute you would
call <emphasis>createAttribute()</emphasis>.
If your class often calls <classname>DocumentFactory</classname> or uses a different DocumentFactory instance
you could add it as a member variable and initiate it via <emphasis>getInstance</emphasis> in your constructor.
</para>

<programlisting width="59">

import org.dom4j.DocumentFactory;
import org.dom4j.Document;
import org.dom4j.Element;

public class GranuatedDeployFileCreator {

 private DocumentFactory factory;
 private Document doc;

 public GranuatedDeployFileCreator() {
   this.factory = DocumentFactory.getInstance();
 }

 public void generateDoc(String aRootElement) {
    doc = factory.createDocument();
    Element root = doc.addElement(aRootElement);
 }

}

</programlisting>



<para>
The <classname>Document</classname> and <classname>Element</classname>
interfaces have a number of helper methods for creating an XML document programmatically
in a simple way.
</para>

<programlisting width="59">

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Foo {

  public Document createDocument() {
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement( "root" );

    Element author2 = root.addElement( "author" )
      .addAttribute( "name", "Toby" )
      .addAttribute( "location", "Germany" )
      .addText( "Tobias Rademacher" );

    Element author1 = root.addElement( "author" )
      .addAttribute( "name", "James" )
      .addAttribute( "location", "UK" )
      .addText( "James Strachan" );

    return document;
  }
}

</programlisting>



<para>
As mentioned earlier <application>dom4j</application> is an interface based API.
This means that DocumentFactory and the reader classes in the org.dom4j.io package always use the org.dom4j interfaces
rather than any concrete implementation classes.
The Collection API and <acronym>W3C</acronym>'s <acronym>DOM</acronym> are other examples of APIs that
use this design approach.
This widespread design is described by <citation>BillVenners</citation>.
</para>

</chapter>

<chapter>
<title>Serialization and Output</title>

<para>
Once you parsed or created a document you want to serialize it to disk or
into a plain (or encrypted) stream. <application>dom4j</application> provides a set of classes to serialize
your dom4j tree in four ways:
</para>

<itemizedlist>
  <listitem><para>XML</para></listitem>
  <listitem><para>HTML</para></listitem>
  <listitem><para>DOM</para></listitem>
  <listitem><para>SAX Events</para></listitem>
</itemizedlist>

<section><title>Serializing to XML</title>
<classname>org.dom4j.io.XMLWriter</classname> is a easy-to-use and easy-to-understand class used
to serialize a <application>dom4j</application> tree to a plain <acronym>XML</acronym>.
You are able
to write the <acronym>XML</acronym> tree to either an <classname>java.io.OutputStream</classname>
or a <classname>java.io.Writer</classname>.
This can be configured with the overloaded constructor or via the
<classname>setOutputStream()</classname> or <classname>setReader()</classname> methods.
Let's have a look at a example.

<programlisting width="59">

import java.io.OutputStream;

import org.dom4j.Document;
import org.dom4j.io.XMLWriter;
import org.dom4j.io.OutputFormat;

public class DeployFileCreator {

 private Document doc;

 public void serializetoXML(OutputStream out, String aEncodingScheme) throws Exception {
   OutputFormat outformat = OutputFormat.createPrettyPrint();
   outformat.setEncoding(aEncodingScheme);
   XMLWriter writer = new XMLWriter(out, outformat);
   writer.write(this.doc);
   writer.flush();
 }

}
</programlisting>

<para>
We use the <classname>XMLWriter</classname> constructor  to pass
<classname>OutputStream</classname> along with the required character encoding.
It is easier to use a <classname>Writer</classname> rather than an <classname>OutputStream</classname>,
because the <classname>Writer</classname> is String based and so has less
character encoding issues.
The write() methods of <classname>Writer</classname> are overloaded so that you can write all of the dom4j objects individually if required.
</para>


<section><title>Customizing the output format</title>
<para>
The default output format is to write the XML document as-is.
If you want to change the output format then there is a class
<classname>org.dom4j.io.OutputFormat</classname> which allows you to define pretty-printing options,
suppress output of XML declaration, change line ending and so on.
There is also a helper method <classname>OutputFormat.createPrettyPrint()</classname> which
creates a default pretty-printing format that you can further customize if you wish.
</para>


<programlisting width="59">

import java.io.OutputStream;

import org.dom4j.Document;
import org.dom4j.io.XMLWriter;
import org.dom4j.io.OutputFormat;

public class DeployFileCreator {

 private Document doc;

  public void serializetoXML(OutputStream out, String aEncodingScheme) throws Exception {
   OutputFormat outformat = OutputFormat.createPrettyPrint();
   outformat.setEncoding(aEncodingScheme);
   XMLWriter writer = new XMLWriter(out, outformat);
   writer.write(this.doc);
   writer.flush();
 }


}
</programlisting>

<para>
An interesting feature of <classname>OutputFormat</classname> is the ability to set
character encoding. It is a good idiom to use this mechansim for setting the encoding
for XMLWriter to use this encoding to create an OutputStream as well
as to output XML declaration.
</para>

<para>
The <classname>close()</classname> method closes the underlying <classname>Writer</classname>.
</para>

<programlisting width="59">

import java.io.OutputStream;

import org.dom4j.Document;
import org.dom4j.io.XMLWriter;
import org.dom4j.io.OutputFormat;

public class DeployFileCreator {

 private Document doc;
 private OutputFormat outFormat;

 public DeployFileCreator() {
   this.outFormat = OuputFormat.getPrettyPrinting();
 }

 public DeployFileCreator(OutputFormat outFormat) {
   this.outFormat = outFormat;
 }

 public void writeAsXML(OutputStream out) throws Exception {
   XMLWriter writer = new XMLWriter(outFormat, this.outFormat);
   writer.write(this.doc);
 }

 public void writeAsXML(OutputStream out, String encoding) throws Exception {
   this.outFormat.setEncoding(encoding);
   this.writeAsXML(out);
 }

}
</programlisting>

<para>
The serialization methods in our little example  set encoding using <classname>OutputFormat</classname>.
The default encoding if none is specifed is <acronym>UTF-8</acronym>.
If you need a simple output on screen for debugging or testing you can omit setting of
a <classname>Writer</classname> or an <classname>OutputStream</classname> completely
as <classname>XMLWriter</classname> will default to <classname>System.out</classname>.
</para>

</section>

</section>

<section><title>Printing HTML</title>
<para>
<classname>HTMLWriter</classname> takes a <application>dom4j</application> tree
and formats it to a stream as <acronym>HTML</acronym>. This formatter is similar to
<classname>XMLWriter</classname> but outputs the text of CDATA and Entity sections rather than the serialized
format as in <acronym>XML</acronym> and also supports many HTML element which have no corresponding close tag
such as for &lt;BR&gt; and &lt;P&gt;
</para>

<programlisting width="59">

import java.io.OutputStream;

import org.dom4j.Document;
import org.dom4j.io.HTMLWriter;
import org.dom4j.io.OutputFormat;

public class DeployFileCreator {

 private Document doc;
 private OutputFormat outFormat;

 public DeployFileCreator() {
   this.outFormat = OuputFormat.getPrettyPrinting();
 }

 public DeployFileCreator(OutputFormat outFormat) {
   this.outFormat = outFormat;
 }

 public void writeAsHTML(OutputStream out) throws Exception {
   HTMLWriter writer = new HTMLWriter(outFormat, this.outFormat);
   writer.write(this.doc);
   writer.flush();
 }

}
</programlisting>

</section>

<section><title>Building a DOM tree</title>
<para>
Sometimes it's necessary to transform your <application>dom4j</application> tree
into a <acronym>DOM</acronym> tree, because you are currently refactoring your application.
<application>dom4j</application> is very convenient for integration with older <acronym>XML</acronym>
<acronym>API</acronym>'s like <acronym>DOM</acronym> or <acronym>SAX</acronym>
(see <anchor id="dom4j2SAX">Generating SAX Events</anchor>). Let's move to an example:
</para>

<programlisting width="59">
import org.w3c.dom.Document;

import org.dom4j.Document;
import org.dom4j.io.DOMWriter;

public class DeployFileLoaderSample {

  private org.dom4j.Document doc;

  public org.w3c.dom.Document transformtoDOM() {
    DOMWriter writer = new DOMWriter();
    return writer.write(this.doc);
  }
}

</programlisting>

</section>

<section id="dom4j2SAX"><title>Generating SAX Events</title>
<para>
If you want to output a document as sax events in order to integrate with some existing SAX
code, you can use the <classname>org.dom4j.SAXWriter</classname> class.
</para>


<programlisting width="59">
import org.xml.ConentHandler;

import org.dom4j.Document;
import org.dom4j.io.SAXWriter;

public class DeployFileLoaderSample {

  private org.dom4j.Document doc;

  public void transformtoSAX(ContentHandler ctxHandler) {
     SAXWriter writer = new SAXWriter();
     writer.setContentHandler(ctxHandler);
     writer.write(doc);
  }
}

</programlisting>

<para>
As you can see using <classname>SAXWriter</classname> is fairly easy.
You can also pass <classname>org.dom.Element</classname> so
you are able to process a single element branch or even a single node with <acronym>SAX</acronym>.
</para>
</section>
</chapter>

<chapter>
<title>Navigation in dom4j</title>
<para>
dom4j offers several powerful mechanisms for navigating through a document:
</para>

<itemizedlist>
  <listitem><para>Using Iterators</para></listitem>
  <listitem><para>Fast index based navigation</para></listitem>
  <listitem><para>Using a backed List</para></listitem>
  <listitem><para>Using XPath</para></listitem>
  <listitem><para>In-Build GOF Visitor Pattern</para></listitem>
</itemizedlist>

<section><title>Using Iterator</title>
<para>
Most Java developers used java.util.Iterator or it's ancestor
<classname>java.util.Enumeration</classname>.
Both classes are part of the Collection API and used
to visit elements of a collection.
Here is an example of using Iterator:
</para>
</section>

<programlisting width="59">

import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;

public class DeployFileLoaderSample {

  private org.dom4j.Document doc;
  private org.dom4j.Element root;

  public void iterateRootChildren() {
    root = this.doc.getRootElement();
    Iterator elementIterator = root.elementIterator();
    while(elementIterator.hasNext()){
      Element elmeent = (Element)elementIterator.next();
      System.out.println(element.getName());
    }
  }
}
</programlisting>

<para>
The above example might be a little bit confusing if you are not familiar with the Collections API.
Casting is necessary when you want to access the object. In JDK 1.5 Java Generics solve this problem .
</para>

<programlisting width="59">
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;

public class DeployFileLoaderSample {

  private org.dom4j.Document doc;
  private org.dom4j.Element root;

  public void iterateRootChildren(String aFilterElementName) {
    root = this.doc.getRootElement();
    Iterator elementIterator = root.elementIterator(aFilterElementName);
    while(elementIterator.hasNext()){
      Element elmeent = (Element)elementIterator.next();
      System.out.println(element.getName());
    }
  }
}
</programlisting>

<para>
Now the the method iterates on such Elements that have the <emphasis>same name</emphasis> as the parameterized String only. This can be used as a kind of
filter applied on top of Collection API's Iterator.
</para>

<section><title>Fast index based Navigation</title>
<para>
Sometimes if you need to walk a large tree very quickly, creating an <classname>java.io.Iterator</classname>
instance to loop through each <classname>Element</classname>'s children can be too expensive.
To help this situation, <application>dom4j</application> provides a fast index based looping as follows.
</para>

<programlisting width="59">
  public void treeWalk(Document document) {
    treeWalk( document.getRootElement() );
  }

  public void treeWalk(Element element) {
    for ( int i = 0, size = element.nodeCount(); i &lt; size; i++ ) {
      Node node = element.node(i);
      if ( node instanceof Element ) {
        treeWalk( (Element) node );
      }
      else {
        // do something....
      }
    }
  }
</programlisting>


<section><title>Using a backed List</title>
<para>
You can navigate through an <classname>Element</classname>'s children
using a backed <classname>List</classname> so the modifications to the
<classname>List</classname> are reflected back into the <classname>Element</classname>.
All of the methods on <classname>List</classname> can be used.
</para>

<programlisting width="59">
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;

public class DeployFileLoaderSample {

  private org.dom4j.Document doc;

  public void iterateRootChildren() {
    Element root = doc.getRootElement();

    List elements = root.elements;

    // we have access to the size() and other List methods
    if ( elements.size() > 4 ) {
      // now lets remove a range of elements
      elements.subList( 3, 4 ).clear();
    }
  }
}
</programlisting>

</section>

<section><title>Using XPath</title>
<para>
<acronym>XPath</acronym> is is one of the most useful features of <application>dom4j</application>.
You can use it to retrieve nodes from any location as well as evaluating complex expressions.
A good XPath reference can be found in Michael Kay's XSLT book <citation>XSLTReference</citation>
along with the <citation>Zvon</citation> Zvon tutorial.
</para>
</section>

<programlisting width="59">
import java.util.Iterator;

import org.dom4j.Documet;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.XPath;

public class DeployFileLoaderSample {

  private org.dom4j.Document doc;
  private org.dom4j.Element root;

  public void browseRootChildren() {

    /* 
      Let's look how many "James" are in our XML Document an iterate them  
      ( Yes, there are three James in this project ;) )
    */
      
    XPath xpathSelector = DocumentHelper.createXPath("/people/person[@name='James']");
    List results = xpathSelector.selectNodes(doc);
    for ( Iterator iter = result.iterator(); iter.hasNext(); ) {
      Element element = (Element) iter.next();
      System.out.println(element.getName();
    }

    // select all children of address element having person element with attribute and value "Toby" as parent
    String address = doc.valueOf( "//person[@name='Toby']/address" );

    // Bob's hobby
    String hobby = doc.valueOf( "//person[@name='Bob']/hobby/@name" );

    // the second person living in UK
    String name = doc.value( "/people[@country='UK']/person[2]" );
    
    // select people elements which have location attriute with the value "London"
    Number count = doc.numberValueOf( "//people[@location='London']" );
   
  }

}
</programlisting>

<para>
As selectNodes returns a List we can apply <classname>Iterator</classname>
or any other operation avalilable on <classname>java.util.List</classname>.
You can also select a single node via <classname>selectSingleNode()</classname>
as well as to select a String expression via <classname>valueOf()</classname>
or Number
value of an XPath expression via <classname>numberValueOf()</classname>.
</para>


<section><title>Using Visitor Pattern</title>
<para>
The visitor pattern has a recursive behavior and acts like <acronym>SAX</acronym>
in the way that partial traversal is <emphasis>not</emphasis> possible.
This means complete document or complete branch will be visited.
 You should carefully consider situations when you want to use Visitor pattern, but then it
offers a powerful and elegant way of navigation.
This document doesn't explain Vistor Pattern in depth,
<citation>GoF98</citation> covers more information.
</para>

<programlisting width="59">
import java.util.Iterator;

import org.dom4j.Visitor;
import org.dom4j.VisitorSupport;
import org.dom4j.Document;
import org.dom4j.Element;

public class VisitorSample {

  public void demo(Document doc) {

    Visitor visitor = new VisitorSupport() {
      public void visit(Element element) {
        System.out.println(
          "Entity name: " + element.getName()  + "text " + element.getText();
        );
      }
    };

    doc.accept( visitor );
  }
}

</programlisting>

<para>
As you can see we used anonymous inner class to override the
<classname>VisitorSupport</classname> callback adapter method
visit(Element element) and the accept() method starts
the visitor mechanism.
</para>
</section>
</section>
</chapter>


<chapter><title>Manipulating dom4j</title>
<para>
Accessing XML content statically alone would not very special. Thus dom4j offers several methods for manipulation a documents content.
</para>

<section><title>What <classname>org.dom4j.Document</classname> provides</title>
<para>
A <classname>org.dom4j.Document</classname> allows you to configure and retrieve the root element.
You are also able to set the DOCTYPE or a SAX based <classname>EntityResolver</classname>.
An empty <classname>Document</classname> should be created via <classname>org.dom4j.DocumentFactory</classname>.
</para>
</section>

<section><title>Working with <classname>org.dom4j.Element</classname></title>
<para>
<classname>org.dom4j.Element</classname> is a powerful interface providing many methods for manipulating Element.
</para>

<programlisting width="59">

  public void changeElementName(String aName) {
    this.element.setName(aName);
  }

  public void changeElementText(String aText) {
    this.element.setText(aText);
  }

</programlisting>
</section>


  <section><title>Qualified Names</title>
  <para>
  An XML Element should have a qualified name. Normally qualified name consists normally of a Namespace and
  local name. It's recommended to use <classname>org.dom4j.DocumentFactory</classname> to create Qualified
  Names that are provided by <classname>org.dom4j.QName</classname> instances.
  </para>

  <programlisting width="59">

  import org.dom4j.Element;
  import org.dom4j.Document;
  import org.dom4j.DocumentFactory;
  import org.dom4j.QName;

  public class DeployFileCreator {

   protected Document deployDoc;
   protected Element root;

   public void DeployFileCreator()
   {
     QName rootName = DocumentFactory.getInstance().createQName("preferences", "", "http://java.sun.com/dtd/preferences.dtd");
     this.root = DocumentFactory.getInstance().createElement(rootName);
     this.deployDoc = DocumentFactory.getInstance().createDocument(this.root);
   }
  }

  </programlisting>

  </section>

  <section><title>Inserting elements</title>
  <para>
  Sometimes it's necessary to insert an element in a existing XML Tree. This is easy to do using dom4j Collection API.
  </para>

  <programlisting width="59">

    public void insertElementAt(Element newElement, int index) {
      Element parent = this.element.getParent();
      List list = parent.content();
      list.add(index, newElement);
    }

    public void testInsertElementAt() {

    //insert an clone of current element after the current element
      Element newElement = this.element.clone();
      this.insertElementAt(newElement, this.root.indexOf(this.element)+1);

    // insert an clone of current element before the current element
      this.insertElementAt(newElement, this.root.indexOf(this.element));
    }
  </programlisting>

  </section>

<section><title>Cloning - How many sheep do you need?</title>
  <para>
  Elements can be cloned. Usually cloning is supported in Java with clone() method that is derived from <classname>Object</classname>. The cloneable Object has to
  implement interface <classname>Cloneable</classname>. By default clone() method performs shallow copying. dom4j implements  deep cloning
  because shallow copies would not make sense in context of an XML object model. This means that cloning can take a while because the complete tree branch or event the document
  will be cloned. Now have a short look <emphasis>how</emphasis> dom4j cloning mechanism is used.
  </para>

  <programlisting width="59">

  import org.dom4j.Document;
  import org.dom4j.Element;

  public class DeployFileCreator {


   private Element cloneElement(String name) {
    return this.root.element(name).clone();
   }

   private Element cloneDetachElement(String name) {
     return this.root.createCopy(name);
   }

   public class TestElement extends junit.framework.TestCase {

     public void testCloning() throws junit.framwork.AssertionFailedException {
       assert("Test cloning with clone() failed!", this.creator.cloneElement("Key") != null);
       assert("Test cloning with createCopy() failed!", this.creator.cloneDetachElement() != null);
     }
   }
  }
  </programlisting>

  <para>
  The difference between <emphasis>createCopy(...)</emphasis> and <emphasis>clone()</emphasis> is that first method creates a <emphasis>detached</emphasis> deep copy whereas <emphasis>clone()</emphasis> returns exact copy of the current document or element.
  </para>

  <caution><title>Consider use of Cloning</title>
   <para>
   Cloning might be useful when you want to build element pool. Memory consumpsion should be carefully considered during design of such pool.
   Alternatively you can consider to use Reference API <citation>Pawlan98</citation>
    or Dave Millers approach <citation>JavaWorldTip76</citation>.
  </para>
  </caution>

</section>
</chapter>

<chapter><title>Using dom4j with XSLT</title>
<para>
With eXtensible Stylesheet Language XML got a powerfull method of transformation. XML XSL greately simplified job of developing export filters for different data formats. The transformation is done by XSL Processor. XSL covers following subjects:
</para>

<itemizedlist>
  <listitem><para>XSL Style Sheet</para></listitem>
  <listitem><para>XSL Processor for XSLT</para></listitem>
  <listitem><para>FOP Processor for FOP</para></listitem>
  <listitem><para>An XML source</para></listitem>
</itemizedlist>

<para>
Since JaXP 1.1 TraX is the common API for proceeding a XSL Stylesheet inside of Java. You start with a <classname>TransformerFactory</classname>, specify <classname>Result</classname> and <classname>Source</classname>. <classname>Source</classname> contains source xml file that should be transformed. <classname>Result</classname> contains result of the transformation. dom4j offers <classname>org.dom4j.io.DocumentResult</classname> and <classname>org.dom4j.io.DocumenSource</classname> for TrAX compatibility.
Whereas <classname>org.dom4j.io.DocumentResult</classname> contains a <classname>org.dom4j.Document</classname> as result tree, <classname>DocumentSource</classname> takes dom4j <classname>Document</classname>s and prepares them for transformation. Both classes are build on top of TraX own SAX classes. This approach has much better performance than a DOM adaptation. The following example explains the use of XSLT with TraX and dom4j.
</para>

<programlisting width="59">
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;

import org.dom4j.Document;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;

public class DocumentStyler
{
    private Transformer transformer;

    public DocumentStyler(Source aStyleSheet) throws Exception {
        // create transformer
        TransformerFactory factory = TransformerFactory.newInstance();
        transformer = factory.newTransformer( aStyleSheet );
    }

    public Document transform(Document aDocument, Source aStyleSheet) throws Exception {

        // perform transformation
        DocumentSource source = new DocumentSource( aDocument );
        DocumentResult result = new DocumentResult();
        transformer.transform(source, result);

        // return resulting document
        return result.getDocument();
    }
}

</programlisting>

<para>
One could use XSLT to process a XML Schema and generate an empty template xml file according the schema constraints. The code above shows how easy to do that with dom4j and its TraX support. TemplateGenerator can be shared but for this example I avoided this for simplicity. More information about TraX is provided  <ulink url="http://java.sun.com/xml/">here</ulink>.
</para>

</chapter>

<chapter>
<title>Schemata-Support</title>

<para>
First way to describe XML document structure is as old as XML itself.
Document Type Definitions are used since publishing of the XML specification.
Many applications use DTD to describe and validate documents. Unfortunately
the DTD Syntax was not that powerful. Written in SGML, DTDs are also not as easy to handle as
XML.
</para>

<para>
Since then other, more powerful ways to describe XML format were invented.
The W3C published XML Schema Specification which provides significant improvements over DTD.
XML Schemas are described using XML.
A growing group of people use XML Schema now. But XML Schema isn't perfect.
So a few people swear by Relax or Relax NG. The reader of this document is able to choose one of
the following technologies:
</para>

<itemizedlist>
  <listitem><para>Relax NG (Regular Language description for XML Next Generation)<citation>RelaxNG</citation></para></listitem>
  <listitem><para>Relax (Regular Language description for XML)<citation>Relax</citation></para></listitem>
  <listitem><para>TREX<citation>TREX</citation></para></listitem>
  <listitem><para>XML DTDs<citation>DTD</citation></para></listitem>
  <listitem><para>XML Schema<citation>XSD</citation></para></listitem>
</itemizedlist>

<section><title>Using XML Schema Data Types in dom4j</title>
<para>
dom4j currently supports only XML Schema Data Types <citation>DataTypes</citation>.
The dom4j implementation is based on top of MSV. Earlier dom4j releases are built
on top of Sun Tranquilo (xsdlib.jar) library but later moved to MSV now, because MSV
provides the same Tranquilo plus exciting additional features we will discuss later.
</para>

<programlisting width="59">
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.dom4j.dataType.DataTypeElement;

public class SchemaTypeDemo {

public static void main(String[] args) {

  SAXReader reader = new SAXReader();
  reader.setDocumentFactory( DatatypeDocumentFactory.getInstance() );
  Document schema =  return reader.read(xmlFile)
  XPath xpathSelector = DocumentHelper.createXPath("xsd:schema/xsd:complexType[@name='Address']/xsd:structure/xsd:element[@type]");
  List xsdElements = xpathSelector.selectNodes(schema);

  for (int i=0; i &lt; xsdElements.size(); i++) {
    DataElement tempXsdElement = (DatatypeElement)xsdElements.get(i);

    if (tempXsdElement.getData() instanceof Integer) {
       tempXsdElement.setData(new Integer(23));
     }
  }
}
</programlisting>

<caution><title>Alpha status</title>
<para>
Note that the Data Type support is still alpha. If you find any bug, please report it to
the mailing list. This helps us to make more stable Data Type support.
</para>
</caution>

</section>


<section><title>Validation</title>
<para>
Currently dom4j does not come with a validation engine. You are forced to use a external validator.
In the past we recommended Xerces, but now you are
able to use Sun Multi-Schema XML Validator. Xerces is able to validate against DTDs and
XML Schema, but not against TREX or Relax. The Suns Multi Schema Validator supports all mentioned
kinds of validation.
</para>

<caution><title>Consider use of Validation</title>
<para>
Validation consumes valuable resources. Use it wisely.
</para>
</caution>

<section><title>Using Apaches Xerces 1.4.x and dom4j for validation</title>
<para>
It is easy to use Xerces 1.4.x for validation. Download
Xerces from Apaches XML web sites. Experience shows that the newest version
is not always the best.
View Xerces mailing lists in order to find out issues with specific versions.
Xerces provides Schema support strarting from 1.4.0.
</para>

<itemizedlist>
  <listitem><para>Turn on validation mode - which is false for default - using a SAXReader instance</para></listitem>
  <listitem><para>Set the following Xerces property http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation using the schema URI.</para></listitem>
  <listitem><para>Create a SAX XMLErrorHandler and install it to your SAXReader instance.</para></listitem>
  <listitem><para>Parse and validate the Document.</para></listitem>
  <listitem><para>Output Validation/Parsing errors.</para></listitem>
</itemizedlist>

<programlisting width="59">
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.util.XMLErrorHandler;


import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException

public class SimpleValidationDemo {

public static void main(String[] args) {
  SAXReader reader = new SAXReader();

  reader.setValidation(true);

  // specify the schema to use
  reader.setProperty(
   "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
   "prices.xsd"
  );

  // add error handler which turns any errors into XML
   XMLErrorHandler errorHandler = new XMLErrorHandler();
   reader.setErrorHandler( errorHandler );

  // parse the document
  Document document = reader.read(args[0]);

 // output the errors XML
  XMLWriter writer = new XMLWriter( OutputFormat.createPrettyPrint() );
  writer.write( errorHandler.getErrors() );
}

</programlisting>

<caution><title>Xerces and Crimson</title>
<para>
Both, Xerecs and Crimson, are JaXPable parsers. Be careful while using
Crimson and Xerces in same class path. Xerces will work correctly only when it is
specified in class path <emphasis>before</emphasis> Crimson. At this time I
recommend that you should either Xereces <emphasis>or</emphasis> Crimson.
</para>
</caution>

</section>

<section><title>A perfect team - Multi Schema Validator<citation>MSV</citation> and dom4j </title>
<para>
Kohsuke Kawaguchi a developer from Sun created a extremly usefull tool for XML validation.
Multi Schema Validator (MSV) supports following specifications:
</para>

<itemizedlist>
  <listitem><para>Relax NG</para></listitem>
  <listitem><para>Relax </para></listitem>
  <listitem><para>TREX</para></listitem>
  <listitem><para>XML DTDs</para></listitem>
  <listitem><para>XML Schema</para></listitem>
</itemizedlist>

<para>
Currently its not clear whether XML Schema will be the next standard for validation. Relax NG has an ever more growing
lobby. If you want to build a open application that is not fixed to a specific XML parser and specific type of XML validation you should use this powerfull
tool. As  usage of MSV is not trivial the next section shows how to use it in simpler way.
</para>

  </section>
  <section><title>Simplified Multi-Schema Validation by using Java API for RELAX Verifiers (JARV)</title>
  
<para>
The Java API for RELAX Verifiers <citation>JARV</citation> defines a set of Interfaces and provide
a schemata and vendor neutral API for validation of XML documents. The above explained
MSV offers a Factory that supports JARV. So you can use the JARV API on top of MSV and dom4j
to validate a dom4j documents.
</para>

<programlisting>
import org.iso_relax.verifier.Schema;
import org.iso_relax.verifier.Verifier;
import org.iso_relax.verifier.VerifierFactory;
import org.iso_relax.verifier.VerifierHandler;

import com.sun.msv.verifier.jarv.TheFactoryImpl;

import org.apache.log4j.Category;

import org.dom4j.Document;
import org.dom4j.io.SAXWriter;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;

public class Validator {

  private final static CATEGORY = Category.getInstance(Validator.class);
  private String schemaURI;
  private Document document;

  public Validator(Document document, String schemaURI) {
    this.schemaURI = schemaURI;
    this.document = document;
  }
  
  public boolean validate() throws Exception {
  
    // (1) use autodetection of schemas
    VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl();
    Schema schema = factory.compileSchema( schemaURI );
    
    // (2) configure a Vertifier
    Verifier verifier = schema.newVerifier();
        verifier.setErrorHandler(
            new ErrorHandler() {
                public void error(SAXParseException saxParseEx) {
                   CATEGORY.error( "Error during validation.", saxParseEx);
                }
                
                public void fatalError(SAXParseException saxParseEx) {
                   CATEGORY.fatal( "Fatal error during validation.", saxParseEx);
                }
                
                public void warning(SAXParseException saxParseEx) {
                   CATEGORY.warn( saxParseEx );
                }
            }
        );    
        
    // (3) starting validation by resolving the dom4j document into sax     
    VerifierHandler handler = verifier.getVerifierHandler();
    SAXWriter writer = new SAXWriter( handler );
    writer.write( document );   
    
    return handler.isValid();
  }
  
  }
  
}
</programlisting>

<para>
The whole work in the above example is done in <methodname>validate()</methodname> method.
Foremost the we create a <emphasis>Factory</emphasis> instance and use it to create a JAVR 
<classname>org.iso_relax.verifier.Schema</classname> instance.
In second step we create and configure a <classname>org.iso_relax.verifier.Verifier</classname>
using a <classname>org.sax.ErrorHandler</classname>. I use Apaches Log4j API
to log possible errors. You can also use <methodname>System.out.println()</methodname>
or, depending of the applications desired robustness, any other method to provide information about
failures. Third and last step resolves the <classname>org.dom4j.Document</classname>
instance using SAX in order to start the validation. Finally we return a boolean
value that informs about success of the validation. 
</para>

<para>
Using teamwork of dom4j, MSV, JAVR and good old SAX simplifies the usage
of multi schemata validation while gaining the power of MSV.
</para>

  </section>
 </section>
</chapter>

<chapter><title>Declarative Rule Processing</title>
<para>
XSLT defines a declarative rule-based way to transform XML tree into
plain text, HTML, FO or any other text-based format. XSLT is very powerful.
Ironically it does not need variables to hold data.
As Michael Kay <citation>XSLTReference</citation> says: "This style of coding without assignment statements, is
called <emphasis>Functional Programming</emphasis>. The earliest and most
famous functional programming language was Lisp ..., while modern examples
include ML and Scheme." In XSLT you define a so called <emphasis>template</emphasis>
that matches a certain XPath expression. The XSLT Processor traverse the
source tree using a recursive tree descent algorithm and performs the commands you defined when a specific tree branch
matches the template rule.
</para>

<para>
dom4j offers an API that supports XSLT similar rule based processing. The
API can be found in <classname>org.dom4j.rule</classname> package and this 
chapter will introduce you to this powerful feature of dom4j.
</para>

<section><title>Introducing dom4j's declarative rule processing</title>
  <para>
  This section will demonstrate the usage of dom4j's rule API by example.
  Consider we have the following XML document, but that we want to transform
  into another XML document containing less information.  
  </para>
  
  <programlisting>
  <![CDATA[
    <?xml version="1.0" encoding="UTF-8" ?>
    <Songs>
     <song>
       <mp3 kbs="128" size="6128">
         <id3>
          <title>Simon</title>
          <artist>Lifehouse</artist>
          <album>No Name Face</album>
          <year>2000</year>
          <genre>Alternative Rock</genre>
          <track>6</track>     
         </id3>
       </mp3>
      </song>
      <song>
       <mp3 kbs="128" size="6359">
         <id3>
          <title>Hands Clean</title>
          <artist>Alanis Morrisette</artist>
          <album>Under Rug Swept</album>
          <year>2002</year>
          <genre>Alternative Rock</genre>
          <track>3</track>
         </id3>
       </mp3>
      </song>
      <song>
       <mp3 kbs="256" size="6460">
         <id3>
          <title>Alive</title>
          <artist>Payable On Deatch</artist>
          <album>Satellit</album>
          <year>2002</year>
          <genre>Metal</genre>
          <track/>
         </id3>
       </mp3>
       <mp3 kbs="256" size="4203">
         <id3>
          <title>Crawling In The Dark</title>
          <artist>Hoobastank</artist>
          <album>Hoobastank (Selftitled)</album>
          <year>2002</year>
          <genre>Alternative Rock</genre>
          <track/>
         </id3>
       </mp3>
     </song>
    </Songs>
  ]]>
  </programlisting>

  <para>
   A common method to transform one XML document into another is XSLT. It's quite
   powerful but it is very different from Java and uses paradigms different from OO.
   Such style sheet may look like
   this. 
  </para>

    <programlisting>
    <![CDATA[
      <xsl:stylesheet version="1.0"
           xmlns:xsl="http://www.w3.org/1999/XSL/Transform"    
           xmlns:fo="http://www.w3.org/1999/XSL/Format"
       >    
        <xsl:output method="xml" indent="yes"/>

        <xsl:template match="/">
         <Song-Titles>
           <xsl:apply-templates/>
         </Song-Tiltes>
        </xsl:template>
        
        <xsl:template match="/Songs/song/mp3">     
          <Song>
            <xsl:apply-template/>
          </Song>
        </xsl:template>
    
        <xsl:template match="/Songs/song/mp3/title">
          <xsl:text> <xsl:value-of select="."/> </xsl:text>
        </xsl:template> 
   
      </xsl:stylesheet> 
     ]]>
   </programlisting>

  <para>
  This stylesheet filters all song titles and creates a xml wrapper for it.
  After applying the stylesheet with XSLT processor you will
  get the following xml document.
  </para>


    <programlisting>
    <![CDATA[
      <?xml version="1.0" encoding="UTF-8" ?>
      <Song-Titles>
 	<song>Simon</song>
	<song>Hands Clean</song>
        <song>Alive</song>
        <song>Crawling in the Dark</song>
      </Song-Titles>
     ]]>
   </programlisting>


 <para>
   Okay. Now it's time to present a possible solution using dom4j's rule API. As you
   will see this API is very compact. The Classes you have to write are neither complex nor
   extremely hard to understand. We want to get the same result as your former stylesheet.
 </para>


 <programlistingco>
   <areaspec>
     <areaset id="example.rule.step1" coord="">
       <area id="example.rule.root" coords='32'/>
       <area id="example.rule.doc" coords='33'/>
     </areaset>
     <areaset id="example.rule.step2">
       <area id="example.rule.rule1" coords="35"/>
       <area id="example.rule.rule2" coords="39"/>
     </areaset>
     <areaset id="example.rule.step3">
       <area id="example.rule.pattern1" coords="36"/>
       <area id="example.rule.action1" coords="37"/>
       <area id="example.rule.pattern2" coords="40"/>
       <area id="example.rule.action2" coords="41"/>
     </areaset>
     <areaset id="example.rule.step4">
       <area id="example.rule.actionclass1" coords="55"/>
       <area id="example.rule.actionclass2" coords="64"/>
     </areaset>
     <area id="example.rule.step5" coords="43"/>
     <area id="example.rule.step6" coords="47"/>
   </areaspec> 
 <programlisting>
  import java.io.File;

  import org.dom4j.DocumentHelper;
  import org.dom4j.Document;
  import org.dom4j.DocumentException;
  import org.dom4j.Element;
  import org.dom4j.Node;

  import org.dom4j.io.SAXReader;
  import org.dom4j.io.XMLWriter;
  import org.dom4j.io.OutputFormat;

  import org.dom4j.rule.Action;
  import org.dom4j.rule.Pattern;
  import org.dom4j.rule.Stylesheet;
  import org.dom4j.rule.Rule;

  public class SongFilter {
    
    private Document resultDoc;
    private Element songElement;
    private Element currentSongElement;
    private Stylesheet style;
    

    public SongFilter() {
        this.songElement = DocumentHelper.createElement( "song" );
    }

    
    public Document filtering(org.dom4j.Document doc) throws Exception {
        Element resultRoot = DocumentHelper.createElement( "Song-Titles" );
        this.resultDoc = DocumentHelper.createDocument( resultRoot );               
        
        Rule songElementRule = new Rule();
        songElementRule.setPattern( DocumentHelper.createPattern( "/Songs/song/mp3/id3" ) );
        songElementRule.setAction( new SongElementBuilder() );
        
        Rule titleTextNodeFilter = new Rule();
        titleTextNodeFilter.setPattern( DocumentHelper.createPattern( "/Songs/song/mp3/id3/title" ) );
        titleTextNodeFilter.setAction( new NodeTextFilter() );
        
        this.style = new Stylesheet();
        this.style.addRule( songElementRule );
        this.style.addRule( titleTextNodeFilter );
        
        style.run( doc );
        
        return this.resultDoc;
    }
    
    
    
    
    private class SongElementBuilder implements Action {
        public void run(Node node) throws Exception {
           currentSongElement = songElement.createCopy();
           resultDoc.getRootElement().add ( currentSongElement );
           
           style.applyTemplates(node);
        }
    }
    
    private class NodeTextFilter implements Action {       
        public void run(Node node) throws Exception {
          if ( currentSongElement != null )
          {
            currentSongElement.setText( node.getText() );
          }
        }        
    }
        
      
}
 </programlisting>
 <calloutlist>
   <callout arearefs="example.rule.step1">
     <para>Define the root element or another container element for the filtered out information.</para> 
   </callout>
   <callout arearefs="example.rule.step2">
     <para>Create as many instances of <classname>org.dom4j.rule.Rule</classname> as needed.</para> 
   </callout>
   <callout arearefs="example.rule.step3">
     <para>
     Install for each rule a instance of <classname>org.dom4j.rule.Pattern</classname> and 
     <classname>org.dom4j.rule.Action</classname>. A <classname>org.dom4j.rule.Pattern</classname>
     consists of a XPath Expression, which is used for Node matching.
     </para>
   </callout>
   <callout arearefs="example.rule.step4">
     <para>A <classname>org.dom4j.rule.Action</classname> defines the process if a matching occured.</para> 
   </callout>
   <callout arearefs="example.rule.step5">
     <para>Create a instance of <classname>org.dom4j.rule.Stylesheet</classname></para> 
   </callout>
   <callout arearefs="example.rule.step6">
     <para>Start the processing</para> 
   </callout>
</calloutlist>
</programlistingco>

  
 <!--para>
  Following steps are recommended to use this API correctly.
 </para>
   
 <itemizedlist>
  <listitem><para>Define root element or another container element for the filtered out information.</para></listitem>
  <listitem><para>Create as many instances of <classname>org.dom4j.rule.Rule</classname> as needed.</para></listitem>
  <listitem>
    <para>
    Install for each rule a instance of <classname>org.dom4j.rule.Pattern</classname> and 
    <classname>org.dom4j.rule.Action</classname>. A <classname>org.dom4j.rule.Pattern</classname>
    consists of a XPath Expression, which is used for Node matching.
    </para>
  </listitem>
  <listitem><para>A <classname>org.dom4j.rule.Action</classname> defines the process if a matching occurred.</para></listitem>
 </itemizedlist-->

 <para>
   If you are familiar with Java Threads you may encounter usage similarities between <classname>java.lang.Runnable</classname> and <classname>org.dom4j.rule.Action</classname>.
   Both act as a plugin or listener. And this Observer Pattern has a wide
   usage in OO and especially in Java.
   We implemented observers here as private inner classes. You may decide to declare them as outer classes as well. 
   However if you do that, the design becomes more complex because you need to share instance of 
   <classname>org.dom4j.rule.StyleSheet</classname>.
 </para>
   
 <note><title>Anonymous adapters</title>
 <para>
  Moreover it's possible to create an anonymous inner class for <classname>org.dom4j.rule.Action</classname> interface.
 </para>
 </note>
  
</section>

<section><title>Understanding dom4j's rule API</title>

<para>
<table frame="all"><title>Comparing Visitor with Rule API</title>
  <tgroup cols="2" align="left" colsep="0" rowsep="0">
  <colspec colname="c1"/>
  <colspec colname="c2"/>
  <colspec colname="c3"/>
  <colspec colnum="5" colname="c5">
	  <spanspec spanname="hspan" namest="c1" nameend="c2" align="center"/>
  </colspec>	  
  <thead>
  <row>
    <entry spanname="hspan">Visitor</entry>
    <entry spanname="hspan">Declartive Rule Processing</entry>
  </row>
</thead>
<tbody>
<row>
  <entry>Use of Interfaces in design</entry>
  <entry>Use of Interfaces in design</entry>
</row>
<row>
  <entry>Uncontrolled automatic recursive descent traversal</entry>
  <entry>Rule controlled automatic recursive descent traversal</entry>
</row>
<row>
  <entry>Needs knowledge of Visitor pattern to understand</entry>
  <entry>Knowledge of Observer/Publish-Subscriber pattern (ligua franca pattern besides Singleton) useful</entry>
</row>
<row>
  <entry>Provides adapater class to simplify usage of interface</entry>
  <entry>Adapter not necessary due to interface using single method</entry>
</row>
<row>
  <entry>Basic knowledge of dom4j's tree object model necessary</entry>
  <entry>Additional XPath knowlege for pattern specification necessary</entry>
</row>
<row>
  <entry>Implementation is more compact</entry>
  <entry>More code necessary to define the rules and action</entry>
</row>
<row>
  <entry>High and easy modularity</entry>
  <entry>High modularity for controlled recursive processing, but more complex handling if you abandon inner or anonymous inner classes.</entry>
</row>
</tbody>
</tgroup>
</table>   
</para>


<para>
As shown above, dom4j's uses a very flexible OO-Representation of a XSLT Stylesheet. The smart handling of actions
produces compact code.
</para>

<para>
The rule API is a OO representation of W3C XSLT. The API defines another way of traversing the in-memory dom4j tree.
The traversal algorithm is called <emphasis>recursive descent</emphasis> and is the same as XSLT defines. Such algorithms 
are also used in compiler construction and described in literature. 
</para>

<para>
XSLT defines a way of tree merging or filtering. If you output an eXtensible stylesheet result to another xml you merge an
existing tree to another one using the instruction of the Stylesheet and if output to plain text a styling is used for
filtering. First usage is addressed by this API. The second is also possible but not so easy to implement as in XSLT.
</para>

<para>
How does the rule API work? Each Stylesheet has a rule. A rule consists of an action and a pattern. Patterns are described
with XPath. You start the processing of a Stylesheet on a specific source with must be a dom4j <classname>Node</classname>.
Calling method <classname>style.applyTemplates(node);</classname> traverses the <classname>Node</classname> using 
a recursive descent algorithm - branch after branch. If a pattern matches the assigned action is activated.
</para>

<para>
If you are interested more in the way a xml document is traversed by XSLT processors I recommend 
Michael Kay's book <citation>XSLTReference</citation>.
</para>

</section>

</chapter>

<bibliography>
  <title>Further Reading</title>
<bibliodiv><title>Books</title>
<biblioentry>
  <abbrev>XSLTReference</abbrev>
  <authorgroup>
    <author><firstname>Michael</firstname><surname>Kay</surname></author>
  </authorgroup>
  <copyright><year>2001</year>
    <holder>Worx Press, Inc.</holder>
  </copyright>
  <isbn>1-861-005067</isbn>
  <publisher>
     <publishername>Worx Press</publishername>
  </publisher>
  <title>XSLT Programmer's Reference 2'nd Edition</title>
  <seriesinfo>
    <title>Programmer To Programmer</title>
    <publisher>
      <publishername>Worx Press</publishername>
    </publisher>
  </seriesinfo>
</biblioentry>
<biblioentry>
  <abbrev>GoF95</abbrev>
  <authorgroup>
    <author><firstname>Erich</firstname><surname>Gamma</surname></author>
    <author><firstname>Richard</firstname><surname>Helm</surname></author>
    <author><firstname>Ralph</firstname><surname>Johnson</surname></author>
    <author><firstname>John</firstname><surname>Vlissides</surname></author>
  </authorgroup>
  <copyright><year>1995</year>
    <holder>Addison Wesley Pub, Co.</holder>
  </copyright>
  <isbn>0-201-633-612</isbn>
  <publisher>
     <publishername>Addison-Wesley</publishername>
  </publisher>
  <title>Design Patterns: Elements of Reusable Object-Orientated Software</title>
</biblioentry>
</bibliodiv>
</bibliography>
<bibliodiv><title>Articles</title>
<biblioentry>
  <abbrev>Pawlan98</abbrev>
  <authorgroup>
    <author><firstname>Monica</firstname><surname>Pawlan</surname></author>
  </authorgroup>
  <copyright><year>1998</year>
    <holder>http://developer.java.sun.com/javatips/jw-tips76.html</holder>
  </copyright>
  <title>Reference Objects and Garbage Collection</title>
</biblioentry>
<biblioentry>
  <abbrev>JavaTip76</abbrev>
  <authorgroup>
    <author><firstname>Dave</firstname><surname>Miller</surname></author>
  </authorgroup>
  <copyright>
    <holder>http://www.javaworld.com/javaworld/javatips/jw-javatip76.html</holder>
  </copyright>
  <title>An alternative to the deep copying technique</title>
</biblioentry>
<biblioentry>
  <abbrev>BillVenners</abbrev>
  <authorgroup>
    <author><firstname>Bill</firstname><surname>Venners</surname></author>
  </authorgroup>
  <copyright>
    <holder>http://www.artima.com/designtechniques/interfaces.html</holder>
  </copyright>
  <title>Designing with Interfaces - One Programmer's Struggle to Understand the Interface</title>
</biblioentry>
<biblioentry>
  <abbrev>Zvon</abbrev>
  <copyright>
    <holder>http://www.zvon.org/xxl/XPathTutorial/General/examples.html</holder>
  </copyright>
  <title>Zvon XPath tutorial</title>
</biblioentry>
<biblioentry>
  <abbrev>RelaxNG</abbrev>
  <copyright>
    <holder>http://www.oasis-open.org/committees/relax-ng/</holder>
  </copyright>
  <title>Developing RELAX NG, the next generation schema language for XML: clean, simple and powerful</title>
</biblioentry>
<biblioentry>
  <abbrev>Relax</abbrev>
  <copyright>
    <holder>http://www.xml.gr.jp/relax/</holder>
  </copyright>
  <title>The offical site of Relax</title>
</biblioentry>
<biblioentry>
  <abbrev>TREX</abbrev>
  <copyright>
    <holder>http://www.thaiopensource.com/trex/</holder>
  </copyright>
  <title>TREX - Tree Regular Expressions for XML</title>
</biblioentry>
<biblioentry>
  <abbrev>DTD</abbrev>
  <copyright>
    <holder>http://www.w3schools.com/dtd/default.asp</holder>
  </copyright>
  <title>Document Type Definitions Tutorial</title>
</biblioentry>
<biblioentry>
  <abbrev>XSD</abbrev>
  <copyright>
    <holder>http://www.w3.org/XML/Schema http://www.w3.org/XML/1998/06/xmlspec-report</holder>
  </copyright>
  <title>XML Schema</title>
</biblioentry>
<biblioentry>
  <abbrev>JARV</abbrev>
  <copyright>
    <holder>http://iso-relax.sourceforge.net/JARV/</holder>
  </copyright>
  <title>Java API for RELAX Verifiers</title>
</biblioentry>
</bibliodiv>
</book>



