简体   繁体   English

Google Chrome中的XPath错误?

[英]XPath Bug in Google Chrome?

I need to access a XML document I created with JavaScript via XPath. 我需要通过XPath访问使用JavaScript创建的XML文档。 If I load an XML file from a server (via XMLHttpRequest) it works fine, but if I use the XML document reference from the local created XML document Chrome didn't show anything, while Firefox did what I expected. 如果我从服务器上加载XML文件(通过XMLHttpRequest),则可以正常工作,但是如果我使用本地创建的XML文档中的XML文档引用,Chrome不会显示任何内容,而Firefox可以满足我的预期。

Here a bit of example code: 这里是一些示例代码:

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<script type="text/javascript">
        var xml = document.implementation.createDocument("", "", null);

        var root = xml.createElement("root");

        var level1 = xml.createElement("L1");
        var level2 = xml.createElement("L2");
        L2txt = xml.createTextNode("here is L2");

        level2.appendChild(L2txt);
        level1.appendChild(level2);

        var level2 = xml.createElement("L2");
        level2.setAttribute("id", "myId");
        L2txt = xml.createTextNode("here is L2 with id");

        level2.appendChild(L2txt);
        level1.appendChild(level2);
        root.appendChild(level1);

        path="//L2[@id='myId']";

        var nodes=xml.evaluate(path, root, null, XPathResult.ANY_TYPE, null);
        var result=nodes.iterateNext();

        while (result) {
          document.write(result.textContent);
          document.write("<br />");
          result=nodes.iterateNext();
        }
</script>
</body>
</html>

the Code should output "here is L2 with id". 代码应输出“这是带ID的L2”。

I use FF 9.0.1 and Chrome 16.0.912.75 m the development tools don't show any error or hint. 我使用FF 9.0.1和Chrome 16.0.912.75 m,开发工具没有显示任何错误或提示。

Now I don't realy know, is it a bug in Chrome or an 'extra' feature in Firefox. 现在我真的不知道,这是Chrome中的错误还是Firefox中的“额外”功能。 And - most importent - how could I bring Chrome round to act like Firefox. 而且-最重要的是-我该如何使Chrome像Firefox那样运转。 Or do you have another idea how to use XPath on local created XML documents?! 还是您有另一个想法,如何在本地创建的XML文档上使用XPath?

Thanks in advance 提前致谢

I see you have a small problem in your example code. 我看到您的示例代码中有一个小问题。

The root element is never added to the XML document (the xml variable). root元素永远不会添加到XML文档中( xml变量)。

Therefore the XPath search cannot work since the xml document object has no root element and therefore no content to search. 因此,XPath搜索无法工作,因为xml文档对象没有根元素,因此也没有要搜索的内容。 Try adding : 尝试添加:

xml.appendChild(root);

After this: 在这之后:

var root = xml.createElement("root");

That fixes the issue for me in Chrome. 这可以在Chrome中为我解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM