2010-12-10 76 views
0

我可以直接使用jQuery读取XML Feed,但是当我使用'console.log'显示返回XML文档时,'description'标签只显示'#cdata-section'在控制台中,但是当我将它们放入HTML时,它能够显示完整的内容。输出是一篇文章的完整内容,如下面的“示例内容”。通过jQuery读取XML(读取变量)

样本含量:

<p> line 1 line 1 line 1</p> 
<p> line 2 line 2 line 2</p> 
<img src='..' /> 
<p> ... ... </p> 

现在,如果我使用jQuery经由阿贾克斯检索它,我将使用一个“降序”变量来保存这个“描述”节点(其保持上述样品含量) ,但是我如何阅读这个'desc'变量中的'p'或'img'元素?

我想获得这个'desc'变量里面的元素,我的目标是读取img标签。有没有办法做到这一点?注意:在放入HTML之前。

XML:

<channel>​ 
<title>​Property​</title>​ 
<link>​</link>​ 
<lastbuilddate>​Wed, 13 Oct 2010 23:50:51 GMT​</lastbuilddate>​ 
<generator>​FeedCreator 1.8.0-dev ([email protected])​</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>​ 

的jQuery:

$.ajax({ 
type: "GET", 
url: "http://feed6.xml", 
dataType: "xml", 
success: function(xml) { 
    console.log(xml); 
    $(xml).find('channel').each(function(){ 
    $(this).find('item').each(function(){ 
    var desc = $(this).find('description').text(); 
    console.log(desc); 
    }); 
}); 
} 
}); 

回答

2

试试这个.....

$(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"); 
    }); 
}); 
+0

@arkchong您是否试过这段代码? – Vivek 2010-12-10 05:10:09

0

好像这个问题是在这一行:

var desc = $(this).find('description').text(); 

而不是使用的.text的()在该行结尾处,尝试.ht毫升(),然后搜索你想要的标签:

var desc = $(this).find('description').html(); 
var theImageYouwant = desc.find('img'); 
+0

不能,它会给我返回一个错误。 – arkchong 2010-12-10 05:01:17

0

$(this).find("description");将返回一个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);