Archive for June, 2011

XPath using Dom4J

Posted: 6 June 2011 in Uncategorized

A while back I wrote a post on how to do XPath in a w3c context. Here’s an equivalent example using dom4j. I’ve even added a little thingy for handling a default namespace (commented out since the original example was for a DCR.

HashMap namespaces = new HashMap();
namespaces.put("html", "http://www.w3.org/1999/xhtml"); // When we have a doctype, html has a default namespace which is fixed 
String titleXPathExpression = /article/title";
if (titleXPathExpression != null && !titleXPathExpression.equals("")) {
     XPath titleXPath = new org.dom4j.xpath.DefaultXPath(titleXPathExpression);
     // titleXPath.setNamespaceURIs(namespaces);
     String title = titleXPath.valueOf(dom4jHowToXMLDocument);
}
Advertisements