<?xml version="1.0" encoding="UTF-8"?>
<faqs title="Frequently Asked Questions">

<part id="general">
  <title>General</title>
    
  <faq id="whats-dom4j">
    <question>What is dom4j?</question>
    <answer>
      <p><i>dom4j</i> is an Open Source XML framework for Java.
      <i>dom4j</i> allows you to read, write, navigate, create and modify 
      XML documents. 
      <i>dom4j</i> integrates with DOM and SAX and is seamlessly integrated 
      with full XPath support.
      </p>
    </answer>
  </faq>

  <faq id="whats-license">
    <question>What is the dom4j license?</question>
    <answer>
      <p>We use an Apache-style open source license which is one of the least
        restrictive licenses around, you can use <i>dom4j</i> to create new products
        without them having to be open source.
      </p>
      <p>You can find a copy of the license <a href="license.html">here</a>.
      </p>
    </answer>
  </faq>

  <faq id="classpath">
    <question>What do I need to add to my CLASSPATH?</question>
    <answer>
      <p>The dom4j.jar only contains the dom4j classes. If you want to use a SAX parser,
         you'll have to include the SAX classes and the SAX parser of your choice to your
         CLASSPATH. If you want to use XPath expressions, you also have to include the
         jaxen.jar to your CLASSPATH.
      </p>
      <p><i>dom4j</i> can use your existing XML parser and/or DOM implementation 
        (such as <a href="http://xml.apache.org/crimson/">Crimson</a> or 
        <a href="http://xml.apache.org/xerces-j/">Xerces</a> if you want it to. <i>dom4j</i> can also use
        <a href="http://java.sun.com/xml/">JAXP</a> to configure which SAX Parser to use - just add the 
        jaxp.jar to your CLASSPATH and whichever SAX parser you wish away you go.
      </p>
    </answer>
  </faq>

  <faq id="whats-dom4j-v-dom">
    <question>How does dom4j relate to DOM?</question>
    <answer>
      <p>DOM is a quite large language independent API.
        <i>dom4j</i> is a simpler, lightweight API making extensive use of standard Java APIs such as the 
        Java 2 collections API.
      </p>
      <p>Remark that <i>dom4j</i> fully supports the DOM standard allowing both APIs to be 
        used easily together.
      </p>
    </answer>
  </faq>

  <faq id="whats-dom4j-v-jdom">
    <question>How does dom4j relate to JDOM?</question>
    <answer>
      <p><i>dom4j</i> is a different project and different API to JDOM
        though they both have similar goals. They both attempt to make it easier
        to use XML on the Java platform. 
        They differ in their design, API and implementation.
      </p>
      <p><i>dom4j</i> is based on Java interfaces so that plug and play 
        document object model implementations are allowed and encouraged
        such as small, read only, quick to create implementations or 
        bigger, highly indexed fast to naviagte implementations or 
        implementations which read themselves lazily from a database or 
        Java Beans etc.
      </p>
      <p><i>dom4j</i> uses polymorphism extensively such that all document object types 
        implement the Node interface. 
        Also both the Element and Document interfaces can be used polymorphically
        as they both extend the Branch interface.
      </p>

      <p><i>dom4j</i> is fully integrated with XPath support throughout the API 
        so doing XPath expressions is as easy as
      </p>
<pre>
SAXReader reader = new SAXReader();
Document document = reader.read( url );
List links = document.selectNodes( "//a[@href]" );
String title = document.valueOf( "/head/title" );
</pre>
      <p><i>dom4j</i> will soon provide a configuration option to
        support the W3C DOM API natively to avoid unnecessary tree duplication
        when using <i>dom4j</i> with XSLT engines etc.
      </p>
    </answer>
  </faq>

  <faq id="dom4j-sax">
    <question>How does dom4j work with DOM and SAX?</question>
    <answer>
      <p>You can create <i>dom4j</i> documents from XML text, SAX events or existing 
        DOM trees or you can write <i>dom4j</i> documents as SAX events, DOM trees 
        or XML text.
      </p>
    </answer>
  </faq>
</part>


<part id="using">
  <title>Using dom4j</title>
    
  <faq id="dom4j-xslt">
    <question>How can I use XSLT with dom4j?</question>
    <answer>
      <p><i>dom4j</i> integrates with XSLT using the JAXP standard (TrAX) APIs.
        A <i>dom4j</i> Document can be used as the source of XML to be styled or 
        the source of the stylesheet. 
        A <i>dom4j</i> Document can also be used as the result of a transformation. 
      </p>
      <p>First you'll need to use JAXP to load a Transformer.
      </p>
<pre>
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import org.dom4j.Document;
import org.dom4j.DocumentResult;
import org.dom4j.DocumentSource;
...

TransformerFactory factory 
  = TransformerFactory.newInstance();

Transformer transformer 
  = factory.newTransformer( new StreamSource( "foo.xsl" ) );
</pre>
      <p>Now that you have a transformer its easy to style a Document into 
      a new Document.
      </p>
<pre>
DocumentSource source = new DocumentSource( document );
DocumentResult result = new DocumentResult();
transformer.transform( source, result );

Document transformedDoc = result.getDocument();
</pre>
      <p>If you want to transform a Document into XML text you can use JAXP as follows:-
      </p>
<pre>
DocumentSource source = new DocumentSource( document );
DocumentResult result = new StreamResult( new FileReader( "output.xml" ) );
transformer.transform( source, result );
</pre>
      <p>For more information on JAXP and (TrAX) try 
        <a href="http://java.sun.com/xml/">Sun's JAXP site</a>.
      </p>
    </answer>
  </faq>

  <faq id="pretty-print">
    <question>How can I pretty print my XML document?</question>
    <answer>
      <p>You can control the format of the XML text output by
        <a href="apidocs/org/dom4j/io/XMLWriter.html">XMLWriter</a>
        by using the
        <a href="apidocs/org/dom4j/io/OutputFormat.html">OutputFormat</a>
        object.
        You can explicitly set the various formatting options via the 
        properties methods of the OutputFormat object. There is also a helper
        method <code>OutputFormat.createPrettyPrint()</code> which creates 
        the default pretty-print format.
      </p>
      <p>So to pretty print some XML (trimming all whitespace and indenting nicely)
        the following code should do the job...
      </p>
<pre>
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter( out, format );
    writer.write( document );
    writer.close();
</pre>
    </answer>
  </faq>

    
  <faq id="from-string">
    <question>How can I parse a document from a String?</question>
    <answer>
      <p>Sometimes you have a String (or StringBuffer) which contains the XML 
        to be parsed. This can be parsed using <code>SAXReader</code>
        and the <code>StringReader</code> from the JDK. For example:-
      </p>
      <pre>
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

public class Foo {

    public Document getDocument() throws DocumentException {
        return DocumentHelper.parseText( 
            "&lt;root&gt; &lt;child id='1'&gt;James&lt;/child&gt; &lt;/root&gt;"
        );
    }
}
      </pre>
    </answer>
  </faq>


  <faq id="compare-nodes">
    <question>How do I compare 2 nodes for equality?</question>
    <answer>
      <p><i>dom4j</i> by default uses identity based equality for performance.
        It avoids having to walk entire documents or document fragments when
        putting nodes in collections.
      </p>
      <p>To compare 2 nodes (attributes, elements, documents etc) for equality
      the <a href="apidocs/org/dom4j/util/NodeComparator.html">NodeComparator</a> can be
      used.
      </p>
<pre>
    Node node1 = ...;
    Node node2 = ...;
    NodeComparator comparator = new NodeComparator();
    if ( comparator.compare( node1, node2 ) == 0 ) {
        // nodes are equal!
    }
</pre>

    <p>If you are having problems comparing documents that you think
      are equal but the NodeComparator decides that they are different, 
     you might find the following useful.
    </p>

    <p>In dom4j/test/src/org/dom4j/AbstractTestCase.java is-a JUnit TestCase and is
      an abstract base class for dom4j test cases. It contains a whole bunch of
      useful assertion helper methods for testing documents, nodes and fragments
      being equal. The nice thing is that you get useful messages telling you
      exactly why they are different, so its pretty easy to track down.
      For example.
    </p>
<pre>    
public MyTest extends AbstractTestCase {
    ...
    public void testSomething() {
        Document doc1 = ...;
        Document doc2 = ...;

        assertDocumentsEqual( doc1, doc2 );
        ...

        assertNodesEqual( doc1.getRootElement(), doc2.getRootElement() );
    }
}
</pre>
    </answer>
  </faq>

  <faq id="large-doc">
    <question>How does dom4j handle very large XML documents?</question>
    <answer>
      <p><i>dom4j</i> provides an event based model for processing XML documents.
        Using this event based model allows developers to prune the XML tree
        when parts of the document have been successfully processed avoiding
        having to keep the entire document in memory.
      </p>
      <p>For example, imagine you need to process a very large XML file that is 
        generated externally by some database process and looks something like 
        the following (where N is a very large number).
      </p>
      <pre>
<![CDATA[<ROWSET>
    <ROW id="1">
        ...
    </ROW>
    <ROW id="2">
        ...
    </ROW>
    ...
    <ROW id="N">
        ...
    </ROW>
</ROWSET>]]>     
      </pre>
      <p>We can process each &lt;ROW&gt; at a time, there is no 
        need to keep all of them in memory at once.
        <i>dom4j</i> provides a <i>Event Based Mode</i> for this purpose. 
        We can register an event handler for one or more path expressions.
        These handlers will then be called on the start and end of each path
        registered against a particular handler.  When the start tag of a 
        path is found, the onStart method of the handler registered to the 
        path is called.  When the end tag of a path if found, the onEnd method 
        of the handler registered to that path is called.
      </p>
      <p>
        The onStart and onEnd methods are passed an instance of an ElementPath,
        which can be used to retrieve the current Element for the given path.
        If the handler wishes to "prune" the tree being built in order to 
        save memory use, it can simply call the detach() method of the current
        Element being processed in the handlers onEnd() method.
      </p>
      <p>
        So to process each &lt;ROW&gt; individually we can do the following.
      </p>
      <pre>
// enable pruning mode to call me back as each ROW is complete
SAXReader reader = new SAXReader();
reader.addHandler( "/ROWSET/ROW", 
    new ElementHandler() {
        public void onStart(ElementPath path) {
            // do nothing here...    
        }
        public void onEnd(ElementPath path) {
            // process a ROW element
            Element row = path.getCurrent();
            Element rowSet = row.getParent();
            Document document = row.getDocument();
            ...
            // prune the tree
            row.detach();
        }
    }
);

Document document = reader.read(url);

// The document will now be complete but all the ROW elements
// will have been pruned.
// We may want to do some final processing now
...
      </pre>
    </answer>
  </faq>


  <faq id="visitor">
    <question>Does dom4j support the Visitor Pattern?</question>
    <answer>
      <p>Yes. <i>dom4j</i> supports the visitor pattern via the 
          <a href="apidocs/org/dom4j/Visitor.html">Visitor</a> interface.
      </p>
      <p>Here is an example.
      </p>
      <pre>
protected void foo(Document doc) {
  
    // lets use the Visitor Pattern to 
    // navigate the document for entities

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

    doc.accept( visitor );
}
      </pre>
    </answer>
  </faq>


  <faq id="sort-select">
    <question>Can I sort the List returned by Node.selectNodes()?</question>
    <answer>
      <p>Yes. The selectNodes() is a really useful feature to allow nodes to be
        selected from any object in the <i>dom4j</i> object model via an XPath expression. 
        The List that is returned can be sorted by
        specifying another XPath expression to use as the sorting comparator.
      </p>
      <p>
      For example the following code parses an XML play and finds all the
      SPEAKER elements sorted in name order. 
      </p>
      <pre>
SAXReader reader = new SAXReader();
Document document = reader.read( new File( "xml/much_ado.xml" ) );
List speakers = document.selectNodes( "//SPEAKER", "." );
      </pre>
      <p>
      In the above example the name of the SPEAKER is
      defined by the XPath expression "." as the name is stored in the text 
      of the SPEAKER element. 
      If the name was defined by an attribute called "name" then 
      the XPath expression "@name" should be used for sorting.
      </p>
      <p>
      You may wish to remove duplicates while sorting such that (for example)
      the distinct list of SPEAKER elements is returned, sorted by name.
      To do this add an extra parameter to the selectNodes() method call.
      </p>
      <pre>
List distinctSpeakers = document.selectNodes( "//SPEAKER", ".", true );
      </pre>
    </answer>
  </faq>

  <faq id="whats-optional">
    <question>What features are optional in dom4j?</question>
    <answer>
      <p>In <i>dom4j</i> being able to navigate up a tree towards the parent
        and to be able to change a tree are optional features. 
        These features are optional so that an implementation
        can create memory efficient read only document models which
        conserve memory by sharing imutable objects (such as interning 
        Atttributes).
      </p>
        
      <p>There are some helper methods to determine if optional features are 
        implemented. 
        Here is some example code demonstrating their use.
      </p>
      <pre>
protected void foo(Node node) {
  
    // can we do upward navigation?
    if ( ! node.supportsParent() ) {
        throw new UnsupportedOperationException(
          "Cannot navigate upwards to parent"
        );
    }
    Element parent = node.getParent();

    System.out.println( "Node: " + node 
        + " has parent: " + parent 
    );

    if ( parent != null ) {

        // can I modify the parent?
        if ( parent.isReadOnly() ) {
            throw new UnsupportedOperationException(
              "Cannot modify parent as it is read only"
            );
        }

        parent.setAttributeValue( "bar", "modified" );
    }
}
      </pre>
    </answer>
  </faq>

  <faq id="why-jaxp-warning">
    <question>What does the following mean 'Warning: Error occurred using JAXP to load a SAXParser. Will use Aelfred instead'</question>
    <answer>
      <p>
        If dom4j detects JAXP on the classpath it tries to use it to load a SAX parser. 
        If it can't load the SAX parser via JAXP it then tries to use the 
        <code>org.xml.sax.driver</code> system property to denote the SAX parser to use.
        If none of the above work dom4j outputs a warning and continues, using its own 
        internal Aelfred2 parser instead. 
      </p>
      <p>
        The following warning is a result of JAXP being in the classpath but either 
        an old JAXP1.0 version
        was found (rather than JAXP 1.1) or there is no JAXP configured parser 
        (such as crimson.jar or xerces.jar) on the classpath. 
      </p>
<pre>
Warning: Error occurred using JAXP to load a SAXParser. Will use Aelfred instead
</pre>
      <p>        
        So the warning generally indicates an incomplete JAXP classpath and is 
        nothing to worry excessively about.
        If you'd like to see the full verbose reason why the load of a JAXP 
        parser failed then you can try setting the system property 
        <code>org.dom4j.verbose=true</code>. e.g.
      </p>
<pre>
java -Dorg.dom4j.verbose=true MyApp
</pre>
      <p>And you should see a verbose list of why the load of a SAX parser 
        via JAXP failed. 
      </p>
      
      <p>
        To avoid this warning happening either remove the jaxp.jar 
        from your classpath or add a JAXP 1.1. jaxp.jar together with a JAXP 1.1
        parser such as crimson.jar or xerces.jar
        to your classpath.
      </p>
    </answer>
  </faq>


  <faq id="what-parser">
    <question>What XML parser does dom4j use?</question>
    <answer>
      <p>dom4j works with any SAX parser via JAXP. So putting 
        a recent distribution of crimson.jar or xerces.jar on 
        the CLASSPATH will allow Crimson or Xerces's parser to be used.
      </p>
      <p>If no SAX parser is on the classpath via JAXP or the SAX
        org.xml.sax.driver system property then the embedded Aelfred 
        distribution will be used instead. Note that the embedded
        Aelfred distribution is a non validating parser, though it is quite fast
      </p>
    </answer>
  </faq>

  <faq id="how-validate">
    <question>How can I validate my document?</question>
    <answer>
      <p>If a recent version of crimson.jar or xerces.jar is on the CLASSPATH 
      then dom4j will use that as the SAX parser via JAXP. 
      If none of these are on the CLASSPATH then a bundled version of Aelfred is used, 
      which does not validate.
      </p>

      <p>So to perform DTD validation when parsing put crimson.jar or xerces.jar on 
        the CLASSPATH. If you wish to validate against an XML Schema then try xerces.jar.
        Then use the following code.</p>

<pre>
// turn validation on
SAXReader reader = new SAXReader(true);
Document document = reader.read( "foo.xml" );
</pre>

		<p>
		Note: if you want to validate against an XML Schema with xerces, 
		you need to enable the XML Schema validation with the "setFeature" method.
		For more information about
		<a href="http://xml.apache.org/xerces2-j/features.html">xerces features</a>
		visit the xerces website.
		Below is a code sample to enable XML Schema validation.
		</p>

<pre>
// turn validation on
SAXReader reader = new SAXReader(true);
// request XML Schema validation
reader.setFeature("http://apache.org/xml/features/validation/schema", true);
Document document = reader.read( "foo.xml" );
</pre>


      <p>An alternative approach is to use Sun's MSV library for validation, 
      which allows you to use DTD, XML Schema, Relax NG, Relax or TREX as the 
      schema languages. 
      There's an example in the daily build at dom4j/src/samples/validate/JARVDemo.java
      </p>

      <p>If you are validating an existing dom4j document then we recommend 
      you try MSV as it avoids turning the document into text and then parsing 
      it again - MSV can work purely off of SAX events generated from the dom4j document.
      </p>

      <p>Using this approach your code will actually be based on the 
        <a href="http://iso-relax.sourceforge.net/JARV/">JARV</a> API 
        which allows alternative validation mechanisms to
        be plugged into your code.
      </p>		
    </answer>
  </faq>

  <faq id="import-vaj">
    <question>How do I import dom4j into VAJ?</question>
    <answer>
    
    <p>VisualAge for Java checks all dependencies in a JAR and displays
      warnings if there are any unresolved links.
      To avoid any warnings the following steps should be followed
      (thanks to Jan Haluza for this).
    </p>
    <ol>
      <li>Uninstall all the packages having anything in common with the xml 
        (com.ibm.xml* , org.w3c.dom ..) (these packages contains older
        definitions DOM ver. 1 ...
      </li>
      <li>Install the following jars<pre>
dom4j.jar
xalan.jar
PullParser.jar  
relaxng.jar
msv.jar
isorelax.jar
xsdlib.jar
crimson.jar
</pre>
      </li>
    </ol>
    </answer>
  </faq>

  <faq id="cannot-find-dtd">
    <question>Cannot find DTD; how can I tell dom4j where to find the DTD from a DOCTYPE?</question>
    <answer>
    
	<p>
A common way around this is to implement a SAX EntityResolver to load the
DTD from somewhere else. e.g. you could include the DTD in your JAR with
your java code and load it from there.
	</p>

<pre>
EntityResolver resolver = new EntityResolver() {
    public InputSource resolveEntity(String publicId, String systemId) {
        if ( publicId.equals( "-//Acme//DTD Foo 1.2//EN" ) ) {
            InputStream in = getClass().getResourceAsStream(
                "com/acme/foo.dtd"
            );
            return new InputSource( in );
        }
        return null;
    }
};

SAXReader reader = new SAXReader();
reader.setEntityResolver( resolver );
Document doc = reader.parse( "foo.xml" );
</pre>
    </answer>
  </faq>

</part>
</faqs>









