2011-07-13 2 views
2

JavaScriptでいくつかのXMLを解析しているときに私は奇妙な結果を得ています。私はスクリプトを実行するとJavascript:childNodes.lengthに要素が多すぎますか?

function testFunc() 
{ 
    var xhrRsp = 'failed to initialize'; 
    rslt = document.getElementById('rslt'); 
    if(xhr.readyState == 4) 
     { 
     if(xhr.status == 200) 
     { 
      xhrRsp = xhr.responseXML; 
      xhrTree = xhrRsp.documentElement.childNodes; 
      rslt.innerHTML = xhrRsp + ' (' + xhrTree.length + ' nodes) '; 
      for(var i = 0; i < xhrTree.length; i++) 
      { 
       if(xhrTree[i].nodeName != '#text') 
       { 
        rslt.innerHTML = rslt.innerHTML + '<br/>' + xhrTree[i].nodeName + ' (' + xhrTree[i].nodeType + ') ' + ' = ' + xhrTree[i].childNodes[0].nodeValue; 
       } 
      } 
      //rslt.innerHTML = outMsg; 
     } 
    } 
    else 
    { 
     xhrRsp = 'Loading...'; 
    } 
} 

:それは、ページにXMLHttpRequestを経由してファイルをつかん後

<?xml version="1.0" encoding="UTF-8" ?> 

<alerts> 
<alert><![CDATA[ This is the first alert message in a series... ]]></alert> 
<alert><![CDATA[ This is the second alert message in a series, which features a <a href="http://www.facebook.com" target="blank">hyperlink</a>... ]]></alert> 
<alert><![CDATA[ This is the third alert message in a series, which features <span class="emphasizedAlertText">text formatted via a css rule</span> ]]></alert> 
<alert><![CDATA[ This is the fourth alert message in a series, which features a <span class="fauxHyperlink" onclick="someFunction();">javascript call</span>... ]]></alert> 
</alerts> 

、私は出力に以下の機能を持っている:私は外部ファイルに次のXMLを持っていますブラウザ、私は結果としてこれを取得する:

Click Me 
[object Document] (9 nodes) 
alert (1) = This is the first alert message in a series... 
alert (1) = This is the second alert message in a series, which features a hyperlink... 
alert (1) = This is the third alert message in a series, which features text formatted via a css rule 
alert (1) = This is the fourth alert message in a series, which features a javascript call... 

私は、ノードの数が9として戻ってくると、これらの理由は、他のすべての1は私が現在てるの#text、などで来る理由として困惑していますフィルタリング上記のスクリプトで外に出てください。私は周りを見回していて、何が欠けているのか分からない。

ありがとうございます!

+0

字下げしてください。参照してください、これはいつか便利なコードを読んで;) – deadalnix

+0

スクリプトは完璧です。 ''には、9つの子要素、4つの要素ノード、5つのテキストノードがあります。要素ノードのみを出力しています。私はあなたの問題を理解していない... –

答えて

3

これは、W3C準拠のブラウザの正しい動作です。要素間の空白はDOMにTextNodeとして含まれています。

IE8以下では、テキストノードが生成されないことがあります。これは、これらのブラウザがこの点で仕様に準拠していないためです。

+0

ありがとうパトリックとフェリックス。私はそれが私が行方不明だった何か簡単かもしれないと思った。 – Eric

+0

@エリック:どうぞよろしくお願いいたします。 – user113716

0

私はあなたが白い空白を処理することのない厄介なブラウザでそれを実行すると思います。

とにかく、ifでノードをフィルタリングしているので、これは驚くべきことではありません。いくつかの迅速なロギングはあなたの問題に非常に迅速に答えることができます。 。

関連する問題