XPath with JDom

January 11, 2013

I wanted to find a particular node in an XML document and extract data from it, using Java. I'm using jdom as my standard XML parser. The technology used for finding nodes in an XML document is XPath.

In my case I was looking for all the nodes in the document with the tag name FacilityList. I also had a namespace on the nodes, but didn't know what it would be. The XPath expression that will match this is //*:FacilityList.

Unfortunately, this is XPath 2.0, and the version of JDom I was working with only supported XPath 1.0. I could achieve the same result in XPath 1.0 with //* [local-name() = FacilityList]. XPath expressions can be developed using the Oxygen XML editor.

Here is the JDom based Java Code used to select the node:

lXPathExpression = "//* [local-name() = FacilityList]";

Document lDocument = lBuilder.build(new StringReader(pXmlDocumentString));
Element lRootElement = lDocument.getRootElement();

XPath lOutputXPath = XPath.newInstance(lXPathExpression);
Element lFacilityListNode = lOutputXPath.selectSingleNode(lRootElement);

List<Element> lFacilityNodes = lFacilityListNode.getChildren();
for(Element lEachFacility : lFacilityNodes)
{
  String lProductName = lEachFacility.getChild("ProductName", lFacilityListNode.getNamespace());
  If ("BLAH".equals(lProductName))
  { 
    lOtherValue = lEachFacility.getChild("OtherTagName", lFacilityListNode.getNamespace());
  }
}

References

Tags: jdom xpath