Javascript: How to parse xml, write to html5 local storage, then read from local storage, and allow user to search content.

This simple example will demonstrate how to use javascript to write to, and read from, html5 local storage.

The file being parsed and saved is books.xml.  There are two html pages here, LAUNCH.html and OFFLINE.html.

LAUNCH.html will parse the xml file and write it to the user’s browser:

OFFLINE.html will allow the user to search the content of their local storage

LAUNCH.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
 
<body>
 
This page will parse and save books.xml into the users browser<br />
specifically into html5 localStorage<br />
The xml file being pushed is called books.xml<br />
<br />
<a href="books.xml">books.xml</a>
<br />
<a href="OFFLINE.html">OFFLINE.html</a>
 
 
<script type="text/javascript">  
 
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML; 
 
var xmlRowString = "";
 
for (var i = 0; i < xmlDoc.documentElement.childNodes.length; i++)
{
if ( xmlDoc.documentElement.childNodes[i].nodeName == 'book' )
{
for ( var k = 0 ; k < xmlDoc.documentElement.childNodes[i].childNodes.length; k++ )
{
if ( xmlDoc.documentElement.childNodes[i].childNodes[k].nodeName == 'author' )
{
xmlRowString += "<book><author>"+xmlDoc.documentElement.childNodes[i].childNodes[k].textContent+"</author>";
}
if ( xmlDoc.documentElement.childNodes[i].childNodes[k].nodeName == 'title' )
{
xmlRowString += "<title>"+xmlDoc.documentElement.childNodes[i].childNodes[k].textContent+"</title>";
}
if ( xmlDoc.documentElement.childNodes[i].childNodes[k].nodeName == 'description' )
{
xmlRowString += "<description>"+xmlDoc.documentElement.childNodes[i].childNodes[k].textContent+"</description></book>";
}
}
}
if ( xmlRowString === "" )
{
}
else
{
//Here for each book we populate a local stoage row
if (typeof(localStorage) == 'undefined' ) 
{
alert('Your browser does not support HTML5 localStorage. Try upgrading.');
} 
else 
{
try                          
{ 
localStorage.setItem(i, xmlRowString);
} 
catch (e) 
{
alert("save failed!");
if (e == QUOTA_EXCEEDED_ERR) 
{
alert('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
}
xmlRowString = "";	
}
}
 
</script>
 
</body>
</html>

OFFLINE.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Search local storage</title>
</head>
 
<body>
 
This page will allow the user to search the content saved in your local storage.<br />
Search By Author name, results will be returned by book title.<br />
 
 
<form action="OFFLINE.html" method="get">
  Search By Author : <input type="text" name="txtA" /><br />
  <input type="submit" value="Submit" />
</form> 
<br />
<br />
 
 
<div id="results_ID"></div>
 
<script type="text/javascript">
 
var localStorageRow = localStorage.getItem(localStorage.key(i)) ;
 
var author_query = getUrlVars()["txtA"];
 
if (typeof(author_query) == "undefined" || author_query === "" )
{
}
else
{
for ( var i = 0 ; i < localStorage.length;  i++)
{
var localStorageRow = localStorage.getItem(localStorage.key(i)) ;
 
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(localStorageRow,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(localStorageRow);
} 
 
for ( var k = 0 ; k < xmlDoc.firstChild.childNodes.length ; k++ )
{
if ( xmlDoc.firstChild.childNodes[k].nodeName === "author" )
{
 
var auth_row = xmlDoc.firstChild.childNodes[k].textContent;			
var authMatch = auth_row.match(new RegExp(author_query, "i"));
if ( authMatch )
{
//CANNOT USE XPATH(a lot of browsers dont support this) 
//YOU HAVE TO LOOP THOUGH ELEMENTS (again) TO GET TITLE
/*
var nodesSnapshot = document.evaluate('//title', xmlDoc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );  
for ( var q=0 ; q < nodesSnapshot.snapshotLength; q++ )  
{  
document.getElementById("results_ID").innerHTML += nodesSnapshot.snapshotItem(q).textContent+"<br />";
}  
*/
 
for ( var p = 0 ; p < xmlDoc.firstChild.childNodes.length ; p ++ )
{
if ( xmlDoc.firstChild.childNodes[p].nodeName == 'title' )
{
document.getElementById("results_ID").innerHTML += xmlDoc.firstChild.childNodes[p].textContent+"<br />";
}
}
 
}
}
}
}
}
 
//GET URL VARS function
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
 
</script>
 
</body>
</html>

10 thoughts on “Javascript: How to parse xml, write to html5 local storage, then read from local storage, and allow user to search content.

  1. Jean-Marc Flamand

    Thank for the article

    Question
    if the pages are on a web server and the book.xml is on my PC
    How can we access the file on my pc using HTML tags and perform the search

    Reply
    1. Stefano

      What you should do is upload book.xml and it’s definition file (if available) via ftp to the same web server where the pages are. Then the pages can find the XML file.

      Reply
    1. MantasCode Post author

      Yes. But you should check your mobile browser’s html5 capabilities here : http://html5test.com/

      Beneath the category of Storage, look for a green check mark next to Local Storage.

      Reply
  2. Roger

    I´ve tryed it on my pc and why it doesn´t return the book title(it doesn´t return nothing)?

    Reply
  3. xmlstarter

    Hi, thanks a lot for sharing this. It helped me a lot.
    One question : in the end of offline.html I would rather like to print the book Id corresonding to the author rather than the book title.
    For ex : when you search Matthew I would like to print bk101 rather than the title of the book

    How can I do that ? thanks a lot in advance

    Reply
  4. kadjia

    Hi thanks for a great tutorial.
    If we take it a bit further – how can we do the following though?

    – how do you save new data i.e. from a form to the xml file OR local storage (if offline)?
    – how do you sync with the xml file (automatically) – when you get back online?
    – if you wanted to save images, do you store the actual files in local storage? (in which case the storage limit will soon be reached)
    OR
    do you just store references to the images?

    Thanks,
    K.

    Reply
    1. Snehil

      Hi Kadjia ,
      Did you get the solution for how to save new data from a form to xml (if offline ).
      Please let me know , I need to implement this .
      I am facing same problem .
      Thanks .

      Reply
  5. rash

    Hello. I’ve been learning xml with Javascript but it is really difficult for me to use it offline. I have tried your code but it doesn’t return anything. I have also tried to change this line of codes xmlhttp.open(“GET”,”books.xml”,false); into the path where I have saved the books.xml but it can’t still open the xml doc. It just displays the search bar.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *