1
<!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="service@jscript.com" 
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

4

1 回答 1

0

有很多库可以让您使用 Javascript 读取和解析 XML 文件。

一种方法是将 XML 转换为 JSON 并对其进行解析。

Sam Tsvilik 有一个漂亮的小库,可以独立使用或作为 jQuery 插件使用。

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

于 2012-09-24T14:18:27.823 回答