1
votes

I am using Xerces 2.9.1 to perform some XML parsing. The XML contains namespace and I configured Xerces to be namespace aware.

I have two prefixe defined, rec and com. rec is defined in the root tag and com is declared in each node that uses it.

<rec:root xmlns:rec="...">
   <rec:dummy ...>
      <com:item xmlns:com="..." />
    ...

I get an exception when parsing the following XPath expression:

/rec:root/rec:dummy/com:item

XPathStylesheetDOM3Exception: Prefix must resolve to a namespace: com

I found this on a blog, it talks about Xalan but I observe that Xerces has the same behavior.

Well, you might argue a design flaw, since it only uses the mapping found at the node passed to it, i.e., to top level namespace declarations in our case. So, let us move the namespace declaration to the top level, to get the following XML input

Source

Moving the xmlns:com to the root tag fix the issue but I do not have control on that file.

2
Isn't there a way to hand the XPath processor your own prefix-namespace mapping? This sounds like a good idea anyway, you shouldn't rely on the prefix being the same in every input file.millimoose

2 Answers

4
votes

the xpath prefixes have no relation to the prefixes used in the document. you need to provide a "prefix to namespaces" mapping to the xpath handler. using standard java DOM tools, you would provide a NamespaceContext to the XPath instance.

2
votes

Assuming you use the DOM Level 3 XPath API then you need to write a class implementing http://xerces.apache.org/xerces2-j/javadocs/api/org/w3c/dom/xpath/XPathNSResolver.html which then returns the right namespace URI when a prefix used in the XPath expression needs to be resolved. That XPathNSResolver then needs to be passed as the third argument to the evaluate method http://xerces.apache.org/xerces2-j/javadocs/api/org/w3c/dom/xpath/XPathEvaluator.html#evaluate%28java.lang.String,%20org.w3c.dom.Node,%20org.w3c.dom.xpath.XPathNSResolver,%20short,%20java.lang.Object%29. As already pointed out, the prefixes in the path expression do not need to be the same as in the XML input document, you simply need to make sure the XPathNSResolver maps prefixes used in the path expressions to the namespace URIs used in the XML document.