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



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

How to jQuery XML parsing, store in HTML5 LocalStorage and read from LocalStorageHow to jQuery XML parsing, store in HTML5 LocalStorage and read from LocalStorage

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>'
How to jQuery XML parsing, store in HTML5 LocalStorage and read from LocalStorageHow to jQuery XML parsing, store in HTML5 LocalStorage and read from LocalStorage

Topics :

Disclaimer: The content published in this article is the views of the author only. Techglimpse does not gurantee accuracy, completness or validity. If you believe the content on this post violates your copyright, please send us a mail to [email protected] for removal. Read more.