XPath Problems - why can't I match elements?
XPath Problems - why can't I match elements?
April 30, 2011 - 08:33
Here is some XML code:
<CxF xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://colorexchangeformat.com/CxF3-core" xsi:schemaLocation="http://colorexchangeformat.com/CxF3-core CxF3_Core.xsd">
<FileInformation>
<Creator>X-Rite - RFW</Creator>
<CreationDate>2009-08-18T12:15:33-05:00</CreationDate>
<Description>Example CXF3 file</Description>
</FileInformation>
<Resources>
<ObjectCollection>and some Java code
XPath xpath = xPathFactory.newXPath();
XPathExpression expr = xpath.compile("*");
Object result = expr.evaluate(documentElement, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
if (nodes.getLength() < 1)
{
getLogger().error("not found");
}
for (int i = 0; i < nodes.getLength(); i++) {
getLogger().info(" node name = " + nodes.item(i).getNodeName());
}which produces
[2011-04-30 08:18:15,845] INFO 95[main] - node name = FileInformation
[2011-04-30 08:18:15,845] INFO 95[main] - node name = Resources
[2011-04-30 08:18:15,845] INFO 95[main] - node name = CustomResourcesNow, if I change
XPathExpression expr = xpath.compile("*");to
XPathExpression expr = xpath.compile("FileInformation");
XPathExpression expr = xpath.compile("//FileInformation");
XPathExpression expr = xpath.compile("/CxF/FileInformation");
XPathExpression expr = xpath.compile("/*/FileInformation");or any number of permutations that should work, I always get
[2011-04-30 08:28:48,739] ERROR 97[main] - not foundI've been playing around with this for hours, and as far as I can tell, it is impossible to match any element names. Is there some configuration problems I am missing somewhere?





The problem is that your XML document defines an XML namespace identified by the URL "http://colorexchangeformat.com/CxF3-core"
(In fact, it is a default namespace, since it uses no prefix.)
Thus, there is actually no root node "CxF", but rather a root node "someUndefinedNamespacePrefix:CxF".
You need to do the following things in order to make your XPath expression work:
1. Make sure your document was parsed with namespace-awareness switched on (See download.oracle.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilderFactory.html#setNamespaceAware(boolean)).
2. Implement the interface download.oracle.com/javase/6/docs/api/javax/xml/namespace/NamespaceContext.html and map the namespace URL to an arbitrary prefix.
3. Tell the XPath about your namespace context, using download.oracle.com/javase/6/docs/api/javax/xml/xpath/XPath.html#setNamespaceContext(javax.xml.namespace.NamespaceContext)