无法对创建的文档执行 Javascript XPath 查询
问题
我正在使用 javascript 创建一个文档,并且我想对此文档执行 XPath 查询。
- 我已经在 safari/chrome 中尝试过这个
- 我已经阅读了 createDocument / xpath 搜索,看起来这段代码确实应该可以工作
- 此时看来它可能是一个 webkit bug
我的要求:
- 我可以使用innerHTML()来设置文档
- 我可以执行 xpath 搜索 w 标记名
代码:
如果将以下内容复制/粘贴到 webkit 检查器中,您应该能够重现。
function search(query, root) {
var result = null;
result = document.evaluate(query, root, null, 7,null);
var nodes = [];
var node_count = result.snapshotLength;
for(var i = 0; i < node_count; i++) {
nodes.push(result.snapshotItem(i));
}
return nodes;
}
x = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', 'HTML');
body = x.createElement('body');
body.innerHTML = "<span class='mything'><a></a></span>";
xdoc = x.documentElement; //html tag
xdoc.appendChild(body);
console.log(search(".", xdoc)); // --> [<html>…</html>]
console.log(search("/*", xdoc)); // --> [<html>…</html>]
console.log(search("/html", xdoc)); // --> []
最佳猜测
所以我绝对可以使用 XPath 进行搜索,但无法使用标记名进行搜索。我对命名空间有什么愚蠢的想法吗?
Problem
I'm creating a document with javascript and I'd like to execute XPath queries on this document.
- I've tried this in safari/chrome
- I've read up on createDocument / xpath searches and it really seems like this code should work
- At this point it seems like it may be a webkit bug
My requirements:
- I can use innerHTML() to setup the document
- I can execute xpath searches w tagnames
The code:
If you copy/paste the following into the webkit inspector, you should be able to repro.
function search(query, root) {
var result = null;
result = document.evaluate(query, root, null, 7,null);
var nodes = [];
var node_count = result.snapshotLength;
for(var i = 0; i < node_count; i++) {
nodes.push(result.snapshotItem(i));
}
return nodes;
}
x = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', 'HTML');
body = x.createElement('body');
body.innerHTML = "<span class='mything'><a></a></span>";
xdoc = x.documentElement; //html tag
xdoc.appendChild(body);
console.log(search(".", xdoc)); // --> [<html>…</html>]
console.log(search("/*", xdoc)); // --> [<html>…</html>]
console.log(search("/html", xdoc)); // --> []
Best Guess
So I can definitely search using XPath, but I cannot search using tagnames. Is there something silly I'm missing about the namespace?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你尝试过吗:
我对 Safari 不太熟悉,但问题可能是 Safari 在 HTML 之上添加了另一个节点或其他东西。如果是这种情况,前两个查询可能会向您显示该节点及其子节点,这将使它们看起来工作正常,而第三个查询将失败,因为不会有 root=>HTML节点。
只是一个想法。
Have you tried:
I'm not familiar with Safari specifically, but the problem might be that Safari is adding another node above HTML or something. If this was the case, the first two queries might be showing you that node plus it's children, which would make it look like they're working properly, while the third query would fail because there wouldn't be a root=>HTML node.
Just a thought.