2012-04-29 21 views
0

インターネットでこの問題について議論している質問や記事がたくさんあることは知っていますが、どうにかしてこれを動作させることはできません。私は何か基本的なものが欠けていると確信していますが、私はそれを見つけることができません。JavaScriptのXMLパーサーが機能しない

自体を解析:

var str="<article>Some article</article>"; 
:私はこのようなSTRを使用している場合、それは動作します。また

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

、:

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は、と述べています

質問には、それはなぜ機能しないのですか? str変数の末尾に1文字しか追加しなくても、解析は正しく機能しません。また、この動作に関する役に立つチュートリアルを教えてください。

+2

を使用してみては? – gdoron

答えて

4

文字列は複数のルートノードを持つため、有効なXMLではありません。あなたのような何かを意味しました:

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

それが有効なXML構造ではないので...多分

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 .... 
関連する問題