Xpath Doesn't Work In Dynamic Html-document
Solution 1:
The first XPath selects the document root (.
is the current context).
The second one is null because there is no body
at the root context. You could use:
/html/body
or
//body
This will get you the nodes. From there you can get child nodes in context using contextual XPath expressions or DOM methods and properties. To see the node names you can use the nodeName
property on the node you selected:
doc.evaluate(".", doc, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null)
.singleNodeValue.nodeName;
doc.evaluate("//body", doc, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null)
.singleNodeValue.nodeName;
This alternative version uses DOM to create the nodes.
var head = document.createElement("head");
var body = document.createElement("body");
doc.documentElement.appendChild(head);
doc.documentElement.appendChild(body);
It also enforces a namespace (which is ignored in Chrome, in the first example), so the XPath expressions either need to include a namespace mapping function (as the third parameter of the evaluate
method, or ignore them (using wildcards and local name testing as in the example below).
doc.evaluate(".//*[local-name()='body']", doc.documentElement, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue.nodeName
Note that I also used doc.documentElement
as the context node.
Try it in your browser:
Post a Comment for "Xpath Doesn't Work In Dynamic Html-document"