Show guide.html syntax highlighted
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><title>dom4j - Quick Start Guide</title><style type="text/css" media="all">
@import url("./style/maven-base.css");
@import url("./style/maven-theme.css");</style><link rel="stylesheet" href="./style/print.css" type="text/css" media="print"></link><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"></meta><meta name="author" content="James Strachan"></meta><meta name="email" content="jstrachan@apache.org"></meta></head><body class="composite"><div id="banner"><a href="http://sourceforge.net/projects/dom4j" id="organizationLogo"><img alt="MetaStuff Ltd." src="http://sourceforge.net/sflogo.php?group_id=16035"></img></a><a href="http://dom4j.org" id="projectLogo"><img alt="dom4j" src="./images/logo.gif"></img></a><div class="clear"><hr></hr></div></div><div id="breadcrumbs"><div class="xleft">
Last published: 16 May 2005
<span class="separator">|</span>
Doc for 1.6.1
</div><div class="xright">
<a href="http://www.w3.org/TR/xpath" class="externalLink" title="External Link">XPath Spec</a>
<span class="separator">|</span>
<a href="http://jaxen.codehaus.org/" class="externalLink" title="External Link">Jaxen</a>
<span class="separator">|</span>
<a href="http://sourceforge.net/projects/dom4j/" class="externalLink" title="External Link">dom4j@SourceForge</a>
</div><div class="clear"><hr></hr></div></div><div id="leftColumn"><div id="navcolumn"><div id="menudom4j"><h5>dom4j</h5><ul><li class="none"><a href="index.html">Home</a></li><li class="none"><a href="faq.html">FAQ</a></li><li class="none"><strong><a href="guide.html">Quick start</a></strong></li><li class="none"><a href="cookbook.html" class="newWindow" title="New Window" target="_blank">Cookbook</a></li><li class="none"><a href="compare.html">Comparison</a></li><li class="none"><a href="goals.html">Goals</a></li><li class="none"><a href="changes-report.html">Changes</a></li><li class="none"><a href="download.html">Download</a></li><li class="none"><a href="license.html">License</a></li><li class="none"><a href="apidocs/index.html" class="newWindow" title="New Window" target="_blank">Javadoc (1.6.1)</a></li><li class="none"><a href="http://www.dom4j.org/dom4j-1.5.2/apidocs/index.html" class="newWindow" title="New Window" target="_blank">Javadoc (1.5.2)</a></li><li class="none"><a href="http://www.dom4j.org/dom4j-1.4/apidocs/index.html" class="newWindow" title="New Window" target="_blank">Javadoc (1.4)</a></li></ul></div><div id="menuProject_Documentation"><h5>Project Documentation</h5><ul><li class="none"><a href="index.html">About dom4j</a></li><li class="collapsed"><a href="project-info.html">Project Info</a></li><li class="collapsed"><a href="maven-reports.html">Project Reports</a></li><li class="none"><a href="http://maven.apache.org/development-process.html" class="externalLink" title="External Link">Development Process</a></li></ul></div><div id="legend"><h5>Legend</h5><ul><li class="externalLink">External Link</li><li class="newWindow">Opens in a new window</li></ul></div><a href="http://www.cenqua.com/clover" title="Code Coverage by Clover" id="poweredByExternal"><img alt="Code Coverage by Clover" src="http://www.cenqua.com/images/clovered1.gif"></img></a><a href="http://www.sourceforge.net" title="Hosted by SourceForge" id="poweredByExternal"><img alt="Hosted by SourceForge" src="http://sourceforge.net/sflogo.php?group_id=16035&amp;type=1"></img></a><a href="http://maven.apache.org/" title="Built by Maven" id="poweredBy"><img alt="Built by Maven" src="./images/logos/maven-button-1.png"></img></a></div></div><div id="bodyColumn"><div class="contentBox"><div class="section"><a name="Parsing_XML"></a><h2>Parsing XML</h2><p>One of the first things you'll probably want to do is to parse an
XML document of some kind. This is easy to do in <i>dom4j</i>.
The following code demonstrates how to this.
</p><pre>
import java.net.URL;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
public class Foo {
public Document parse(URL url) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(url);
return document;
}
}
</pre></div><div class="section"><a name="Using_Iterators"></a><h2>Using Iterators</h2><p>A document can be navigated using a variety of methods that return
standard Java Iterators. For example
</p><pre>
public void bar(Document document) throws DocumentException {
Element root = document.getRootElement();
// iterate through child elements of root
for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
Element element = (Element) i.next();
// do something
}
// iterate through child elements of root with element name "foo"
for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {
Element foo = (Element) i.next();
// do something
}
// iterate through attributes of root
for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
Attribute attribute = (Attribute) i.next();
// do something
}
}
</pre></div><div class="section"><a name="Powerful_Navigation_with_XPath"></a><h2>Powerful Navigation with XPath</h2><p>In <i>dom4j</i> XPath expressions can be evaluated on the Document
or on any Node in the tree (such as Attribute, Element or
ProcessingInstruction).
This allows complex navigation throughout the document with a single
line of code. For example.
</p><pre>
public void bar(Document document) {
List list = document.selectNodes( "//foo/bar" );
Node node = document.selectSingleNode( "//foo/bar/author" );
String name = node.valueOf( "@name" );
}
</pre><p>For example if you wish to find all the hypertext links in an XHTML document
the following code would do the trick.
</p><pre>
public void findLinks(Document document) throws DocumentException {
List list = document.selectNodes( "//a/@href" );
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
Attribute attribute = (Attribute) iter.next();
String url = attribute.getValue();
}
}
</pre><p>If you need any help learning the XPath language we highly recommend
the <a href="http://www.zvon.org/xxl/XPathTutorial/General/examples.html" class="externalLink" title="External Link">Zvon tutorial</a>
which allows you to learn by example.
</p></div><div class="section"><a name="Fast_Looping"></a><h2>Fast Looping</h2><p>If you ever have to walk a large XML document tree
then for performance we recommend you use the fast
looping method which avoids the cost of creating
an Iterator object for each loop. For example
</p><pre>
public void treeWalk(Document document) {
treeWalk( document.getRootElement() );
}
public void treeWalk(Element element) {
for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
Node node = element.node(i);
if ( node instanceof Element ) {
treeWalk( (Element) node );
}
else {
// do something....
}
}
}
</pre></div><div class="section"><a name="Creating_a_new_XML_document"></a><h2>Creating a new XML document</h2><p>Often in <i>dom4j</i> you will need to create a new document
from scratch. Here's an example of doing that.
</p><pre>
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 author1 = root.addElement( "author" )
.addAttribute( "name", "James" )
.addAttribute( "location", "UK" )
.addText( "James Strachan" );
Element author2 = root.addElement( "author" )
.addAttribute( "name", "Bob" )
.addAttribute( "location", "US" )
.addText( "Bob McWhirter" );
return document;
}
}
</pre></div><div class="section"><a name="Writing_a_document_to_a_file"></a><h2>Writing a document to a file</h2><p>A quick and easy way to write a Document (or any Node) to a Writer
is via the write() method.
</p><pre>
FileWriter out = new FileWriter( "foo.xml" );
document.write( out );
</pre><p>If you want to be able to change the format of the output, such as pretty
printing or a compact format, or you want to be able to work with
Writer objects or OutputStream objects as the destination, then you can use the XMLWriter class.
</p><pre>
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class Foo {
public void write(Document document) throws IOException {
// lets write to a file
XMLWriter writer = new XMLWriter(
new FileWriter( "output.xml" )
);
writer.write( document );
writer.close();
// Pretty print the document to System.out
OutputFormat format = OutputFormat.createPrettyPrint();
writer = new XMLWriter( System.out, format );
writer.write( document );
// Compact format to System.out
format = OutputFormat.createCompactFormat();
writer = new XMLWriter( System.out, format );
writer.write( document );
}
}
</pre></div><div class="section"><a name="Converting_to_and_from_Strings"></a><h2>Converting to and from Strings</h2><p>If you have a reference to a Document or any other Node such as an
Attribute or Element, you can turn it into the default XML text
via the asXML() method.
</p><pre>
Document document = ...;
String text = document.asXML();
</pre><p>If you have some XML as a String you can parse it
back into a Document again using the helper method
DocumentHelper.parseText()
</p><pre>
String text = "<person> <name>James</name> </person>";
Document document = DocumentHelper.parseText(text);
</pre></div><div class="section"><a name="Styling_a_Document_with_XSLT"></a><h2>Styling a Document with XSLT</h2><p>Applying XSLT on a Document is quite straightforward using the
<a href="http://java.sun.com/xml/" class="externalLink" title="External Link">JAXP</a> API from Sun.
This allows you to work against any XSLT engine such as Xalan or SAXON.
Here is an example of using JAXP to create a transformer and then
applying it to a Document.
</p><pre>
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import org.dom4j.Document;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;
public class Foo {
public Document styleDocument(
Document document,
String stylesheet
) throws Exception {
// load the transformer using JAXP
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(
new StreamSource( stylesheet )
);
// now lets style the given document
DocumentSource source = new DocumentSource( document );
DocumentResult result = new DocumentResult();
transformer.transform( source, result );
// return the transformed document
Document transformedDoc = result.getDocument();
return transformedDoc;
}
}
</pre></div></div></div><div class="clear"><hr></hr></div><div id="footer"><div class="xright">© 2001-2005, MetaStuff Ltd.</div><div class="clear"><hr></hr></div></div></body></html>
See more files for this project here