Javascript XML解析器不起作用

时间:2012-04-29 18:59:38

标签: javascript xml parsing dom

我知道有很多问题和文章在互联网上讨论这个问题,但我不知道怎么办这个问题。我很确定我遗漏了一些基本的东西,但我找不到它。

解析本身:

var str="<article>Some article</article><other>Other stuff</other>";
var xmlDoc = null;
if (window.DOMParser) {
            var parser = new DOMParser();
            xmlDoc = parser.parseFromString(str,"text/xml");
        } 
else if (window.ActiveXObject) {
            xmlDoc = new ActiveXObject ("Microsoft.XMLDOM");
            xmlDoc.async = false;
            xmlDoc.loadXML(str);
        }


var node = xmlDoc.getElementsByTagName("article")[0].childNodes[0].nodeValue;
alert (node);

但它不起作用,FF说:

xmlDoc.getElementsByTagName("article")[0] is undefined

此外,如果我使用这样的str:

var str="<article>Some article</article>";

所以问题是,它为什么不起作用?即使我只将一个字符附加到str变量的末尾,解析也不能正常工作。你能否指出一些关于这种行为的有用教程?

2 个答案:

答案 0 :(得分:4)

您的字符串不是有效的XML,因为它有多个根节点。你的意思是:

<article><name>Some article</name><other>Something else</other></article>

答案 1 :(得分:1)

尝试使用

var str="<root><article>Some article</article><other>Other stuff</other></root>";


var node = xmlDoc.documentElement.getElementsByTagName("article")[0].childNodes[0].nodeValue;

documentElement property returns the root tag of an xml document , once you get the root tag, next you can extract elements by tag name , child nodes ....
相关问题