Search code examples
jqueryajaxxmlrsscdata

How to AJAX load a blog image from RSS/XML when img is in CDATA


How to AJAX load blog image from RSS/XML when img is in CDATA?

I can load the title, url, publication date, etc... from our blog rss feed, but I cannot figure out how to target the image. I started with this script and modified it to get this:

$.ajax({
type: "GET",
url: "http://www.example.com/blog/feed",
dataType: "xml",

success: function(xml) {

    var contain = $("div#blogSection");
    var limit = 1;

    $(xml).find('item').each(function(index){
    if( index < limit ){

        var title = $(this).find('title').text();
        var url = $(this).find('link').text();
        var pubDate = $(this).find('pubDate').text();
        var img = $(this).find('content:encoded > p > img').attr('src').text();
        var desc = $(this).find('description > p:first').text();

        $('<div class="blogFeed"></div>').html('<div class="feedThumbnail"><img src="'+img+'" class="resizable" title="blog image" alt="blog image"></div><div class="feedExcerpt"><h3 class="title"><a href="'+url+'">'+title+'</a></h3><p>'+desc+'</p><p><a class="allLink" href="'+url+'" title="read more" alt="read more" target="_blank">read more</a></p></div>').appendTo(contain);
        return;
        }
        });//end each
    }
});

I think the problem is in CDATA within the xml, as I have read that it interprets everything within it as character data. The xml looks something like this:

<item>
    <title>Title</title>
    <link>Link</link>
    <comments>Comments</comments>
    <pubDate>Date</pubDate>
    <description><![CDATA[Description]]></description>
    <content:encoded><![CDATA[<p><img src="http://www.example.com/img.jpg"...]]></content:encoded>
</item>

If I am correct that it is CDATA causing it to not target, what can I do in my ajax code to target the image and the first paragraph? If I am incorrect, should I add/remove?

Thanks!


Solution

  • Working on all browsers:

    I replaced this:

    var img = $(this).find('content:encoded > p > img').attr('src').text();
    

    With this:

    var img = $(this).find('content\\:encoded, encoded').text();
    img = $.parseHTML(img);
    img = img[0].firstChild.src;
    

    I escaped the special character in 'content:encoded' and added ", encoded". After adding $.parseHTML, console.log(img); revealed the location of the src. Returning .text() removed CDATA and I now suspect that CDATA is irrelevant. Days of testing for a blog image. Hope it helps someone else save time.