假设我有以下XML结构:
<root>
<item>
<item1>some text is <b>here</b></item1>
<item2>more text is here</item2>
</item>
</root>
我可以使用以下内容解析xml:
$(responseXML).find('item').each(function(){
var first_text = $(this).find('item1').text();
var second_text = $(this).find('item2').text();
}
但是使用.text()时不会保留html。 html()在jquery中不适用于xml。
有关如何在解析xml时保留内部html的任何想法吗?
答案 0 :(得分:4)
将您不希望在CDATA部分中解释为xml的部分嵌套 e.g。
<root>
<item>
<item1><![CDATA[some text is <b>here</b>]]></item1>
<item2><![CDATA[more text is here]]></item2>
</item>
</root>
编辑:注意,如果使用.text()不起作用,请尝试以下操作:
引自:http://dev.jquery.com/ticket/2425
我刚刚重新遇到这个。对于好奇的我的解决方法而不是使用.text()来使用我创建的这个插件(简单地用.getCDATA()替换.text():
jQuery.fn.getCDATA = function() {
if($.browser.msie)
return this[0].childNodes[0].nodeValue;
// Other browsers do this
return this[0].childNodes[1].nodeValue;
};
它不漂亮,但在我的情况下完成了这项工作。
答案 1 :(得分:3)
Text()
将为您提供节点的文本信息。
但是,如果您使用:
var first_text = $(this).find('item1').html();
var second_text = $(this).find('item2').html();
您也将获得HTML标记。