【问题标题】:Need help parsing xml with javascript需要帮助使用 javascript 解析 xml
【发布时间】: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


【解决方案1】:

你需要沿着层次结构向下走,所以,首先找到Contacts 节点,然后在里面你可以得到所有的标记名。

你有很多属性,所以你可能会发现这也很有用:

node.attributes["url"].nodeValue

所以只需遍历所有项目,然后我只需将itemelem[t] 复制到node 以使其更容易,然后您就可以获得所需的属性。

根据您使用的浏览器,它们中的大多数都带有一些 javascript 调试器,因此您可以设置断点并查看变量中的值,然后看看下一步需要做什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 2014-07-12
    • 2018-12-11
    • 1970-01-01
    相关资源
    最近更新 更多