[英]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>
以下是我的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>
我看不到任何輸出..任何代碼錯誤? 而且我也想從下面的URL中檢索數據,並在HTML中顯示數據,任何建議和有用的鏈接將非常有用
http://maps.googleapis.com/maps/api/geocode/json?address=1600+露天劇場+百匯,+山景+景觀,+ CA&sensor = false
一個Google之外有很多庫,您可以使用Javascript讀取和解析XML文件。
一種方法是將XML轉換為JSON並進行解析。
Sam Tsvilik為此提供了一個漂亮的小庫,可以單獨使用或作為jQuery插件使用。
http://www.terracoder.com/index.php/xml-objectifier/xml-objectifier-introduction
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.