JDOM, Namespaces, and XPath
When using JDOM for XPath expressions, remember the following (source):
The key point to remember is that there is no default namespace in XPath. That is, whether your document uses namespace prefixes or not, you have to use prefixes when referencing namespaces in XPath expressions. These prefixes do not have to match the ones used in the document if you declare the namespace using XPath.addNamespace().
A detailed example is
XPath xp = XPath.newInstance("/ns:Receipt/ns:DateTime");
xp.addNamespace("ns", "http://www.nrf-arts.org/IXRetail/namespace");
Element timestampEl = (Element) xp.selectSingleNode(document);
System.out.println(timestampEl.getValue());
The above code will correctly return the value of the DateTime attribute in the following XML document.
<?xml version="1.0" encoding="UTF-8"?> <Receipt xmlns="http://www.nrf-arts.org/IXRetail/namespace" xmlns:xsi="http:/www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/IXRetail DR_Receipt.xsd"> <Location xsi:type="AddressedParty"> <ContactName> <FirstName></FirstName> <LastName></LastName> </ContactName> <Address> <Street1></Street1> <City></City> <State></State> <PostalCode></PostalCode> </Address> </Location> <TransactionID>0001</TransactionID> <DateTime>0501261151</DateTime> <TotalAmount></TotalAmount> </Receipt>
Note: the above XML doesn’t validate. It has been abbreviated.