How to parse XML using jQuery, store in HTML5 LocalStorage and read from LocalStorage

Updated on September 1, 2017

Creating an app or a website to display top news from various websites is a challenging one. In the process, first retrieving a RSS/XML, parsing it and display it takes quite a long time. To load faster for better user experience, first retrieve the RSS/XML, parse and store data in the LocalStorage, then read from the localstorage and display. Here i will be showing you how easy it is to read XML/RSS using jQuery, store in HTML5 LocalStorage and read later to display. In Live Demo, i have creatively displayed the title and link. You can customize it according to your needs.

jQuery XML Parsing, Storing on LocalStorage and read from LocalStorage to Display
jQuery XML Parsing, Storing on LocalStorage and read from LocalStorage to Display

[sc:demobuttons demolink=”http://demo.techglimpse.com/xml-parsing-and-storing-on-localstorage/” boxlink=”http://adf.ly/PkrKd” ]

How to read XML/RSS using jQuery ?

On web page load, retrieve the RSS/XML file. On successful retrieval, parse the XML file for each item. Here for simplicity i have retrieved title and link. You might be wondering about variable “i” ? This variable is used as key for storing the data onto LocalStorage.

$(document).ready(function(){
 var i=1;
 $.ajax({
 type: "GET",
 url: "http://techglimpse.com/index.php/feed",
 dataType: "xml",
 success: function(xml) {
 $(xml).find('item').each(function(){
 var title = $(this).find('title').text();
 var link = $(this).find('link').text();
 });
 }
 });
});

How to store XML data on LocalStorage ?

Once the XML is parsed, the corresponding information to be stored on localstorage is converted as data objects, which is then stored on the LocalStorage using JSON stringify.

try {
 var personObject = new Object();
 personObject.title = title;
 personObject.link = link;
 personObject.brief = brief;
 localStorage.setItem(i, JSON.stringify(personObject));
}
catch (e) {
 if (e == QUOTA_EXCEEDED_ERR) {
 console.log("Error: Local Storage limit exceeds.");
 }
 else {
 console.log("Error: Saving to local storage.");
 }
}
XML-Storing-on-LocalStorage
XML-Storing-on-LocalStorage

How to Read XML data Stored in LocalStorage for Display ?

 var personObject = JSON.parse(localStorage.getItem(i));
 var div_title = personObject.title;
 var div_link = personObject.link;
 document.getElementById('display').innerHTML += '<a href="'+div_link+'">'+div_title+'</a>'

[sc:demobuttons demolink=”http://demo.techglimpse.com/xml-parsing-and-storing-on-localstorage/” boxlink=”http://adf.ly/PkrKd” ]

Was this article helpful?

Related Articles

Leave a Comment