2

I need to access a XML document I created with JavaScript via XPath. 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.

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".

I use FF 9.0.1 and Chrome 16.0.912.75 m the development tools don't show any error or hint.

Now I don't realy know, is it a bug in Chrome or an 'extra' feature in Firefox. And - most importent - how could I bring Chrome round to act like Firefox. Or do you have another idea how to use XPath on local created XML documents?!

Thanks in advance

ahorn42
  • 125
  • 1
  • 6

1 Answers1

1

I see you have a small problem in your example code.

The root element is never added to the XML document (the xml variable).

Therefore the XPath search cannot work since the xml document object has no root element and therefore no content to search. Try adding :

xml.appendChild(root);

After this:

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

That fixes the issue for me in Chrome.

Todd Ditchendorf
  • 10,531
  • 14
  • 63
  • 119
  • 1
    wow, thank you very much, I don't know why I missed this *-* .. well but Firefox also accepted the old version ... Chrome seems to be very correct ;-) – ahorn42 Jan 21 '12 at 20:46