【发布时间】:2012-02-20 00:24:57
【问题描述】:
首先让我感谢您的帮助,我是 Javascript 新手,想学习将 >.xml 文件解析为我的 javascript。我要解析的文件是contact.xml,位于我的根文件夹中。 再次感谢您。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function loadXMLDoc(XMLname)
{
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",XMLname,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>
*Here is my .xml file*
<?xml version="1.0" encoding="utf-8" ?>
<Contacts>
<item servicephone="(800) 500-0066"
email="customerservice@fsig.com"
url="http://www.fsig.com"
address="5000 Barcilona Beach Rd. Wilmington, NC 28000">
</item>
</Contacts>
【问题讨论】:
-
问题中通常有
?,并说明问题所在。贴一堵“需要帮助”的代码墙,没有其他任何帮助。 -
@marc 我很抱歉。我的问题的主要问题是我得到一个白屏而不是 .xml 中的信息。所以我的问题基本上是,在查看我的编码时,我可以在哪里改进它以便从contactinfo.xml 文件中返回正确的信息?
-
从调试开始,比如看看
M.length是什么。现在你的脚本除了应该生成的 javascript 之外没有可见的输出。然后开始回溯并找出为什么它是 0。
标签: javascript html xml parsing