Display data from XML file using javascript
Sponsored Links
XML: can be used to store data for your web page page. You can create your own tags like the <html> tags. Thus you can create a new language of your own.
Javascript: is client side scripting language , which we used to retrieve the information from XML file.
<?xml version=”1.0″ encoding=”utf-8″?><Contents>
<Quotable><quotes>Vulgarity in a king flatters the majority of the nation.</quotes><author>– George Bernard Shaw</author></Quotable>
<Quotable><quotes>Forgive your enemies, but never forget their names.</quotes></Quotable><Quotable><quotes>Computers are useless. They can only give you answers. </quotes></Quotable>
<Quotable><quotes>The only true wisdom is in knowing you know nothing.</quotes><author>– Socrates</author></Quotable></Contents>Note: Each tag should end with closing tag [</>]
Secondly Create the JavaScript to extract data from XML file called “extract.js, the script should look like
<script lanaguage=”javascript”>if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safarixmlhttp=new XMLHttpRequest();}else{// code for IE6, IE5xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”); }xmlhttp.open(“GET”,”quotes.xml”, false);xmlhttp.send();xmlDoc=xmlhttp.responseXML;var x=xmlDoc.getElementsByTagName(“Quotable”);var str=”";for (i=0;i<x.length;i++){var str= str+” “+x[i].getElementsByTagName(“Quotes”)[0].childNodes[0].nodeValue + ” By “+ x[i].getElementsByTagName(“author”)[0].childNodes[0].nodeValue + “…”;}document.write(“<font size=2 face=Terminal color=white>”);document.write(“<marquee scrolldelay=230>”, str,”</marquee>”);</script>
Now it is time for putting these into webpage (HTML file). Save it as “test1.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><script type=”text/javascript” src=”extract.js”></script></head><body bgcolor=”#000000″><h1>Wise Notes Online School</h1></body></html>
The result: What will be the out put? ”Flash News Passing on the top of the page(html file). You can add additional information to XML file which will displayable in the HTML file. So you can change your content when ever you needs.
Like this post? please share and promote! by clicking below icons:
Labels:
JavaScript,
XML