简体   繁体   English

用javascript解析xml文件

[英]Parsing xml file with javascript

<!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 以下是我的contactinfo.xml文件

<?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 而且我也想从下面的URL中检索数据,并在HTML中显示数据,任何建议和有用的链接将非常有用

http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false http://maps.googleapis.com/maps/api/geocode/json?address=1600+露天剧场+百汇,+山景+景观,+ CA&sensor = false

There are plenty of libraries out there one google away that will allow you to read and parse XML files using Javascript. 一个Google之外有很多库,您可以使用Javascript读取和解析XML文件。

One way to do this is to convert the XML into JSON and parse that. 一种方法是将XML转换为JSON并进行解析。

Sam Tsvilik has a nifty little library for this that can be used standalone or as a jQuery plugin. Sam Tsvilik为此提供了一个漂亮的小库,可以单独使用或作为jQuery插件使用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM