Parsing XML with jQuery using XPath or CSS path or CSS Selectors

Parsing XML with jQuery using XPath or CSS path or CSS Selectors

This is just a continuation to my previous post. I missed a very simple thing in the post. jQuery allows you to use CSS path, commonly known as CSS selectors, which is somewhat similar to XPath. For uninformed, XPath is a simpler way to query nodes in an XML document. You can even use filters with these selectors. Visit this doc page on jQuery doc website for more. Using the same code base I made following changes to access items node from my XML feed file.

//The xpath way
$(xml).find( "channel>item" ).each(
    function(){
        var item = $(this),
        title =  item.find('title').text(),
        link =  item.find('link').text(),
        itemid =  item.attr('id');//get an attribute
        console.log(title);
        console.log(link);
        console.log('The attribute value "' + itemid + '".');
    }
);

I have update the code on github page. How can you

Author: Kumar Chetan Sharma

Run of the mill developer.

1 thought on “Parsing XML with jQuery using XPath or CSS path or CSS Selectors”

Comments are closed.