Monday, March 26, 2012

Parse XML using Javascript

Yahoo API provide some web service. For example, the following link return xml of some information of a place search by text of "New York".
http://query.yahooapis.com/v1/public/yql?q=select*from%20geo.places%20where%20text=%22New%20York%22&format=xml

We can use JavaScript to parse the xml to retrieve information; such as WOEID, placeTypeName, name and much more. The example display WOEID, placeTypeName, name of the first place in the returned list.

Parse XML using Javascript
<html>
<head>
<meta charset="UTF-8">
<title>Mobile-Web-App: XML Parse</title>

<script>

function loadwoeid()
{
 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","http://query.yahooapis.com/v1/public/yql?q=select*from%20geo.places%20where%20text=%22New%20York%22&format=xml",false);
 xmlhttp.send();
 xmlDoc=xmlhttp.responseXML; 
 
 place=xmlDoc.getElementsByTagName("place");
 firstplace = place[0];
 
 woeid=(firstplace.getElementsByTagName("woeid")[0].childNodes[0].nodeValue);
 placetypename=(firstplace.getElementsByTagName("placeTypeName")[0].childNodes[0].nodeValue);
 name=(firstplace.getElementsByTagName("name")[0].childNodes[0].nodeValue);
 
 txt = "<p>WOEID: " + woeid + "</p>" 
   + "<p>placeTypeName: " + placetypename + "</p>" 
   + "<p>name: "+ name +"</p>";
   
 document.getElementById("woeidtable").innerHTML=txt;
}
</script>
</head>
<body onload="loadwoeid()">
<h1>Mobile-Web-App: XML Parse</h1>
<div id='woeidtable'></div>

</body>
</html>

No comments:

Post a Comment