Reputation: 39013
I can't get the browser's XPath evaluator to work, which is very frustrating. I'm pretty sure this is a namespace issue, but I'm not sure what I'm doing wrong.
I have an XML document. I want to execute an XPath query, even a simple one - //teiHeader
. This is a valid query - returning all elements with the teiHeader
tag. The document contains one such element.
Once I parse the XML document, I try to evaluate the XPath expression like so:
const resolver = doc.createNSResolver(doc.documentElement);
const xpathResult = doc.evaluate(xpath, doc, resolver);
let node = xpathResult.iterateNext();
while(node) {
console.log(node);
node = xpathResult.iterateNext();
}
The result is no nodes, the first call to iterateNext
returns null.
You can look at this fiddle that demonstrates the problem. You'll see the XPath evaluation returned no elements, but a simple getElementsByTagName
succeeds. Both Chrome and Firefox behave the same way.
What am I missing here?
Upvotes: 1
Views: 278
Reputation: 1820
The TEI document you are using as source XML contains only a default namespace with no prefix. But in XPath 1.0, you must specify a prefix for each namespace you want to use. The XPath //teiHeader
instead will only select <teiHeader>
elements in no namespace.
If you want to retrieve the teiHeader
element with Document.evaluate()
, you can use this XPath instead:
const xpath = "//*[local-name() = 'teiHeader']"
Upvotes: 1