2012-04-29 76 views
0

我知道有很多问题和文章在互联网上讨论这个问题,但我无法得到这个工作。我很确定我错过了一些基本的东西,但我找不到它。Javascript的XML解析器不起作用

解析本身:

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

也许是因为它不是一个有效的XML结构...? – gdoron

回答

4

由于您的字符串有多个根节点,因此您的字符串无效。你的意思是这样:

<article><name>Some article</name><other>Something else</other></article> 
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 ....