通过jQuery读取XML(读取变量)

通过jQuery读取XML(读取变量),jquery,xml,parsing,variables,cdata,Jquery,Xml,Parsing,Variables,Cdata,我可以使用jQuery直接读取XML提要,但当我使用“console.log”显示返回的XML文档时,“description”标记仅在控制台中显示“#cdata节”,但当我将它们放入HTML中时,它能够显示全部内容。输出是一篇文章的完整内容,如下面的“示例内容” 样本内容: <p> line 1 line 1 line 1</p> <p> line 2 line 2 line 2</p> <img src='..' /> <p&

我可以使用jQuery直接读取XML提要,但当我使用“console.log”显示返回的XML文档时,“description”标记仅在控制台中显示“#cdata节”,但当我将它们放入HTML中时,它能够显示全部内容。输出是一篇文章的完整内容,如下面的“示例内容”

样本内容:

<p> line 1 line 1 line 1</p>
<p> line 2 line 2 line 2</p>
<img src='..' />
<p> ... ... </p>
<channel>​
 <title>​Property​</title>​
 <link>​</link>​
 <lastbuilddate>​Wed, 13 Oct 2010 23:50:51 GMT​</lastbuilddate>​
 <generator>​FeedCreator 1.8.0-dev (info@mypapit.net)​</generator>​
 <atom:link href=​"sample.com" rel=​"self" type=​"application/​rss+xml">​</atom:link>​
 <item>​
  <title>​sample title​</title>​
  <description>​
    #cdata-section
  </description>​
  <pubdate>Wed, 08 Dec 2010 23:04:25 GMT</pubdate>
 </item>​
<channel>​

问题似乎出在这一行:

var desc = $(this).find('description').text();
不要在该行末尾使用.text(),请尝试使用.html(),然后搜索所需的标记:

var desc = $(this).find('description').html();
var theImageYouwant = desc.find('img');
试试这个

$(xml).find('channel').each(function(){
$(this).find('item').each(function(){
var desc=$(this.find('description').text();
var newTag=document.createElement(“div”);
newTag.innerHTML=desc;
var imgTag=newTag.getElementsByTagName(“img”);
});
});
$(此)。查找(“说明”)
将返回jquery包装的XML片段

假设内容不是cdata包装的,您可以像使用html一样使用jquery遍历

e.g. $(this).find("description").find("p").each(function() { // whatever });
如果它是cdata包装的,那么不幸的是,jQuery不支持类似html()的xml函数,但是您可以打开jQuery对象,然后重新包装描述xml节点。大概是这样的:

var content = $($(this).find("description")[0].nodeValue);

是的,我认为这是可行的,但是如果我在内容中有多个img标记,我应该如何得到第一个?如果你有多个图像标记,那么newTag.getElementsByTagName(“img”)将返回数组…所以只需使用for循环迭代,你将得到所有img标记…如果你有img以外的标记,然后你可以得到这些标签,就像我为img标签做的一样…请接受这个答案,如果你觉得它对你有用…谢谢
var content = $($(this).find("description")[0].nodeValue);