在JavaScript中解析一些XML时,我得到了一些奇怪的结果。我在外部文件中有以下XML:
<?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>
通过XMLHttpRequest获取文件后,我有以下函数将其输出到页面:
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...';
}
}
当我在浏览器中运行脚本时,我得到了结果:
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的形式返回,为什么其他每个节点都以#text形式出现,我目前正在上面的脚本中过滤掉。我一直在环顾四周,无法弄清楚我错过了什么。
提前致谢!
答案 0 :(得分:3)
这是符合W3C标准的浏览器的正确行为。元素之间的空格作为TextNode
包含在DOM中。
您可能会发现在IE8及更低版本中,未生成文本节点。这是因为这些浏览器在这方面不符合规范。
答案 1 :(得分:0)
我打赌你在一个糟糕的浏览器上运行它,它不会按原样处理空格。
无论如何,你用if过滤一些节点,所以这并不奇怪。一些快速记录可以非常快速地回答您的问题。 。