从javascript读取xml中的cdata [英] read cdata in xml from javascript
问题描述
<![CDATA [test]]>
我正在空白。
<![CDATA[test]]> I am getting blanks.
var dataNode=Ext.DomQuery.selectNode('data',xml);
console.log(dataNode.childNodes[0].nodeValue);
console.log(dataNode.nodeValue);
推荐答案
虽然我们不能确定没有解析XML的原因,但通常是从 childNodes [0]
( firstChild
)获取空白的原因是,父节点之间有一个空白文本节点起始标签和您要查找的节点:
Whilst we can't say for sure without the XML that's being parsed, the usual reason for ‘getting blanks’ from childNodes[0]
(firstChild
) is that there is a whitespace Text node between the parent's start-tag and the node you are looking for:
<data>
<![CDATA[ foo ]]>
</data>
在保留CDATA部分的XML解析器中,将提供数据
元素的三个子元素:一个包含换行符和一些空格的Text节点; CDATASection节点;还有一个带有换行符的Text节点。
On an XML parser that retains CDATA sections, that'll give the data
element three children: a Text node containing a newline and some spaces; the CDATASection node; and another Text node with a newline.
所以您可以接受 childNodes [1]
,但这有点脆弱...特别是对于XML解析器来说,它会破坏CDATA节成文本,在那里您将得到一个包含 foo
的Text子级。和所有空白。最好采用< data>
元素的 textContent
(当然,回退到 innerText
for IE)。
So you could take childNodes[1]
, but it's a bit fragile... in particular it would break for an XML parser that turns CDATA sections into text, where you'd get a single Text child containing foo
and all the whitespace. Probably better to take the textContent
of the <data>
element (except of course with fallback to innerText
for IE).
这篇关于从javascript读取xml中的cdata的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!