javascript - 使用 XML 文件的标签和属性在 PHP 文档中循环不起作用

标签 javascript xml for-loop

我无法弄清楚为什么这不循环。出于测试目的,我只包含了两个设备标签,其中包含所有这些信息。设备联合是这里的主要标签。这是我的代码:

if (window.XMLHttpRequest)
{
    xhttp=new XMLHttpRequest();
}
else // for IE 5/6
{
    xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","http://stage.pithlabs.com/cat/wp-content/themes/cat-child/test.xml",false);
xhttp.send();
xmlDoc=xhttp.responseXML;
document.write("XML document loaded into an XML DOM Object.");
document.write("<table><tr><th>Equipment ID</th><th>Price</th><th>Dealer Name</th><th>Category</th><th>Features</th><th>Images</th></tr>");
var x=xmlDoc.getElementsByTagName("equipment-syndication");
for (i=0;i<x.length;i++)
{ 
    document.write("<tr><td>");
    document.write(x[i].getElementsByTagName("equipment")[0].getAttribute('id'));
    document.write("</td><td>");
    document.write(x[i].getElementsByTagName("price")[0].childNodes[0].nodeValue);
    document.write("</td><td>");
    document.write(x[i].getElementsByTagName("contact")[0].getAttribute('first-name'));
    document.write(x[i].getElementsByTagName("contact")[0].getAttribute('last-name'));

    document.write("</td><td>");
    document.write(x[i].getElementsByTagName("category-class")[0].getAttribute('name'));

    document.write("</td><td>");
    document.write(x[i].getElementsByTagName("category-class")[0].getAttribute('name'));

    document.write("</td><td>");
    document.write('<img src="'+x[i].getElementsByTagName("photo")[0].childNodes[0].nodeValue+'"><br>'); 
    document.write("</td></tr>");
}
document.write("</table>");

现在我知道一切都是正确的,因为我可以看到前端生成的 xml 文件。我可以看到 ID、姓名、图片……所有这些东西。我是不是把循环弄错了?如果有多个“Equipment”元素标签,应该添加另一行,对吗?

这是我正在使用的 xml 文件的基本结构:

<equipment-syndication>
   <equipment id="">
      <price></price>
      <product></product>
      <features>
         <feature></feature>
         <feature></feature>
      </features>
      <photos></photos>
   </equipment>
   <equipment id="">
      <price></price>
      <product></product>
      <features></features>
      <photos></photos>
    </equipment>
</equipment-syndication>

最佳答案

这一行

var x=xmlDoc.getElementsByTagName("equipment-syndication"); 

仅返回一个元素 - XML 根。您需要将代码更改为

var x=xmlDoc.getElementsByTagName("equipment")

获取所有设备元素。

当然,这也表明 for 循环内部发生了变化,但可能仅在这一行:x[i].getAttribute('id')

关于javascript - 使用 XML 文件的标签和属性在 PHP 文档中循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30064501/

相关文章:

javascript - ReactJS 回调在调用之前被触发

javascript - 如何以更漂亮的方式忽略特定规则?

python - XPath - 如何查询满足属性存在条件的父节点?

xml - 为什么 Scala XML 文字对标签之间的空格敏感?

java - android java onClick 无法执行 Activity 的方法

c - 为什么代码会进入无限循环

javascript - 存储对象列表的正确方法

javascript - 负零是假值吗?

r - 使用 for 循环和 pROC 包在 R 中计算多条 ROC 曲线。在预测字段中使用什么变量?

linux - Bash for 循环参数意外行为