I have an issue parsing an XML feed – The following code attempts to parse an XML feed and populate a page with news data. The issue I have is that the description node is HTML encoded and I need to strip out the src of an img tag contained within it ( just one image tag is contained within each description node).
I have limited knowledge of regular expression – but I tried to use a filter approach to strip out the src code – but the below example doesn’t work.
Any help would be gratefully received as I’m pulling my hair out with this one!
$(xml).find("item").each(function() {
var i = $(xml).find("item").index(this);
var imgStripSrc = $('item:eq(1) description', xml).filter(function() {
return /(?: src=")(.+)(?:")/
})
if (i < 1) {
var newsTitleOne = $('item:eq(0) title', xml).text();
if (newsTitleOne.length > 40) {
newsTitleOne = newsTitleOne.substring(0, 30) + "..";
}
$(".newsIOne .newsText .t").empty();
$(".newsIOne .newsText .t").append(newsTitleOne);
} else {
var newsTitleGen = $('item:eq(' + i + ') title', xml).text();
if (newsTitleGen.length > 80) {
newsTitleGen = newsTitleGen.substring(0, 74) + "..";
}
var newsTitleLinkHid = $('item:eq(' + i + ') link', xml).text();
var newsRow = $('<div class="newsRow"><a href="' + newsTitleLinkHid + '" target="_blank">' + newsTitleGen + '</a><img src=' + imgStripSrc + '/></div>');
$(".newsRows").prepend(newsRow);
}
});
XML example here – http://fb.mobilechilli.com/chilli_news_reviews/NewsReviews%20Build/tstXML.xml
You can make use of the fact that jQuery can build a DOM from an HTML string and therefore you do not need to fiddle with regexes at all. I rewrote your code:
Notes
thisalways refers to the current element you are working on, so in the body ofeach()you do not have to juggle around those$('item:eq(' + i + ') title', xml).$(description, this).text()fetches the HTML string, wrapping it in another$()creates a DOM from it. You can operate on that to find your<img>"…"), use it.each(), no need to find/count it yourself.