开发者

read XML via jQuery (read the variable)

I can directly read the XML Feed using jQuery, but when I display the return XML doc using 'console.log', the 'description' tag only show '#cdata-section' in console, but it is able to display full content when I put them into the HTML. The output is a full content of a article, like below 'Sample Content'.

Sample Content:

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

Now, if I retrieve it via .ajax using jQuery, I will use a 'desc' variable to hold this 'description' node (which holding above sample content), but how I read how many 'p' or 'img' element in this 'desc' variable?

I want to get the what element inside this 'desc' variable, my objective is to read the img tag. is there a way to do it? Note: before put into the body of the HTML.

XML:

<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>​

jQuery:

$.ajax({
 type: "GET",
 url: "http://feed开发者_StackOverflow中文版6.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);
  });
 });
 }
});


try this one.....

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


It seems like the problem is in this line:

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

Instead of using .text() at the end of that line, try .html() and then search for the tag you want:

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


$(this).find("description"); will return you a jquery wrapped XML fragment.

Assuming the content isn't cdata wrapped, you can use jquery traversal just as you would html.

e.g. $(this).find("description").find("p").each(function() { // whatever });

If it is cdata wrapped, then unfortunately jQuery doesn't support a html() like function for xml, but you can unwrap the jquery object and then rewrap the description xml node. Something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜