Excerpt this document show some examples of Java XML elaboration with dom4j

  1. Java XML elaboration with dom4j
    1. XML Parsing
    2. XPath navigation
    3. document creation
    4. Writing document to file
    5. Converting to and from String
    6. Apply XSL-Transform
  2. references

Keywords java, xml, dom4j

Java XML elaboration with dom4j

XML Parsing

// build DOM 
URL url = new URL("<path-to-file>");
SAXReader reader = new SAXReader();
Document document = reader.read(url);

Note: In following code samples, we assume Document document is instantiated.

XPath navigation

XPath expression are powerful for navigate the document tree

process a single node is quite easy

Node node = document.selectSingleNode("/html/head/meta[@name=keywords]");
String content = node.valueOf("@content");

processing multiple nodes requires to use a List

Document document; // assume is instantiated
// all src attributes of any img element
List list = document.selectNodes("//**/img/@src");
// loop the list
for( Iterator it = list.iterator(); it.hasNext();  ){
	Attribute att = (Attribute) it.next();
	String uri = att.getValue();

document creation

You can create a docuemnt from scratch by using the DocumentHelper#createDocuemnt(). Adding nodes and attributes is easy and intuitive.

Document document = DocumentHelper.createDocument();
element root = document.addElement("root");
// add a child
Element elChild1 = root.addElement("child")
	.addText("Nic is the first child);
// add a second child
Element elChild2 = root.addElement("child")
	.addText("Vale is the second child);

Writing document to file

To write a document you can use the Document.write() method

FileWriter fw = new FileWriter("my-out-file.xml");
document.write( fw );

You can change writing formats and parameters. Below there is a code example.

// prepare an output format
OutputFormat format = OutputFormat.createPrettyPrint();
XmlWriter xw = new XMLWriter( System.out, format );
xw.write( document );

Converting to and from String

You can convert a document, or a node into corresponding xml String.

// here  get xml of entire document
String text = document.asXML();

If you have XML in a String, you can get build the represented document

String xmlText ="<root><child>Nich</child><child>Vale</child></root>";
Document doc = DocumentHelper.parseText(xmlText);

Apply XSL-Transform

To apply XSL-Transform to a document you can use the JAXP Api from sun, by using any XSLT engine you want, like Xalan or Saxon.

Document document; //.. assume instantiated
String xslturi; //..
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer( new StreamSource(xslturi) );
// executes the transform
DocumentSource source = new DocumentSource( document );
DocumentResult result = new DocumentResult();
t.transform( source, result );
// get output document
Document output = result.getDocument();