1
votes
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadXMLDoc(XMLname)
{
    var xmlDoc;
    if (window.XMLHttpRequest)
    {
        xmlDoc=new window.XMLHttpRequest();
        xmlDoc.open("GET",contactinfo.xml,false);
        xmlDoc.send("");
        return xmlDoc.responseXML;
    }
    // IE 5 and IE 6
    else if (ActiveXObject("Microsoft.XMLDOM"))
    {
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async=false;
        xmlDoc.load(XMLname);
        return xmlDoc;
    }
    alert("Error loading document!");
    return null;
}
<title>Contacts</title>
</script>
</head>

<body>
<script type="text/javascript">
xmlDoc = loadXMLDoc("\contactinfo.xml") // Path to the XML file;
var M = xmlDoc.getElementsByTagName("item");
for (i=0;i<M.length;i++){
    document.write("<div style='width:450px;'>")
    document.write("<h2>"+xmlDoc.getElementsByTagName("item")[i].childNodes[0].nodeValue+"</h2>");
    document.write("<p>" + xmlDoc.getElementsByTagName("servicephone")[i].childNodes[0].nodeValue+    "</p>");
    document.write("<p><a href='" + xmlDoc.getElementsByTagName("email")[i].childNodes[0].nodeValue   +"</p>);
    document.write("</div>")
}
</script>

</body>
</html>

below is my contactinfo.xml file

<?xml version="1.0" encoding="utf-8" ?>
<Contacts>
<item servicephone="12345678" 
email="[email protected]" 
url="http://www.jscript.com" 
address="1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA">
</item>
</Contacts>

i could not see any output..anything wrong in code? and also i have the want to retrieve data from the below url and show the data in html any suggestions and useful links will be helfull

http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false

1
Do you need quotes around xmlDoc.open("GET",contactinfo.xml,false);? Do you get any errors looking in your javascript console? - Phil H
try declaring character encoding at the document level, <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - Rahul
Isn't activex MSIE-only? - sapht

1 Answers

0
votes

There are plenty of libraries out there one google away that will allow you to read and parse XML files using Javascript.

One way to do this is to convert the XML into JSON and parse that.

Sam Tsvilik has a nifty little library for this that can be used standalone or as a jQuery plugin.

http://www.terracoder.com/index.php/xml-objectifier/xml-objectifier-introduction