2012-02-20 137 views
0

首先让我感谢您的帮助,我是Javascript新手,并且想要学习如何解析> .xml文件到我的javascript中。我想解析的文件是contact.xml,位于我的根文件夹中。 再次,谢谢。需要帮助用javascript解析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="[email protected]" 
url="http://www.fsig.com" 
address="5000 Barcilona Beach Rd. Wilmington, NC 28000"> 
</item> 
</Contacts> 
+0

问题通常在其中有一个'?',并解释问题所在。在“需要帮助”的情况下发布代码墙并没有其他任何帮助。 – 2012-02-20 00:27:52

+0

@marc我很抱歉。我的问题的主要问题是我得到一个白色的屏幕,而不是.xml中的信息。所以我的问题基本上是,在查看我的代码时,我可以在哪里改进它,以便从contactinfo.xml文件返回适当的信息? – 2012-02-20 00:33:54

+0

从一些调试开始,比如看看M.length是什么。现在你的脚本没有可见的输出,除了应该生成的javascript。然后开始回溯并找出为什么它是0。 – 2012-02-20 00:34:59

回答

1

你需要往下走的层次,所以,先找到Contacts节点,那里面有你可以得到所有的标记名,你有。

您有属性的一个很大的,所以你可能会发现这也有用:通过所有的项目

node.attributes["url"].nodeValue 

所以只是循环,那么我将刚才复制itemelem[t]node只是为了使它更容易,那么你获得你需要的属性。

根据您使用的浏览器,大多数浏览器都附带了一些JavaScript调试器,因此您可以放入断点并查看变量中的值,并查看下一步需要做什么。