繁体   English   中英

使用HTML / JS提取特定的XML数据

[英]Pull specific XML Data using HTML/JS

我实际上在将循环写入正确位置时遇到问题。 我已经测试了几天,但是我不知道为什么它不会循环到我想要的地方。

我正在从MSDN导出XML,并尝试对其进行适当的组织。

我的XML看起来像这样:

<Data>
<Product_Key Name="Access 2010 ">
<Key ID="473" Type="Retail" ClaimedDate="10/17/2011">Code1</Key>
<Key ID="473" Type="Retail" ClaimedDate="9/8/2011">Code2</Key>
<Key ID="473" Type="Retail" ClaimedDate="9/7/2011">Code3</Key>
</Product_Key>

<Product_Key Name="Office Professional Plus 2007">
<Key ID="197" Type="Retail" ClaimedDate="10/14/2011">Code1</Key>
<Key ID="197" Type="Retail" ClaimedDate="9/23/2011">Code2</Key>
<Key ID="197" Type="Retail" ClaimedDate="9/23/2011">Code3</Key>
<Key ID="197" Type="Retail" ClaimedDate="9/23/2011">Code4</Key>
<Key ID="197" Type="Retail" ClaimedDate="9/23/2011">Code5</Key>
</Product_Key>
</Data>

我的.js脚本如下所示:

function loadXMLDoc(dname) 
{
if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }
else
  {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}

最后,我的HTML看起来像这样:

<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"> 
</script>

</head>
<body>


<script>
xmlDoc=loadXMLDoc("keys.xml");

document.write("<table border='1'>");

x=xmlDoc.getElementsByTagName('Product_Key');
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getAttribute('Name'));
document.write("</td><td>");
document.write(x[i].getElementsByTagName("Key")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
</script>
</body>
</html>

我确定我所需要的只是标记名“ Key”的另一个循环,并且我已经尝试了很多方法,但是最终没有找到正确的方法。

也许我需要if / then语句,以便它测试下一行是另一个“ Product_Key”还是另一个“ Key” ???

目前,我的输出如下所示:

Access 2010                          Code1
Office Professional Plus 2007        Code1

我想要像这样显示所有代码(但在表中。stackoverflow不支持帖子中的表,因此我必须使用修改后的示例进行修改):

Access 2010                          Code1
                                     Code2
                                     Code3
Office Professional Plus 2007        Code1
                                     Code2
                                     Code3
                                     Code4
                                     Code5

尝试这个:

<script>
    var xmlDoc,
        x,
        y,
        i,
        n;

    xmlDoc=loadXMLDoc("keys.xml");
    x=xmlDoc.getElementsByTagName('Product_Key');
    document.write("<table border='1'>");
    for( i=0; i<x.length; i+=1 ) {
        y = x[i].getElementsByTagName("Key");
        for( n=0; n<y.length; n+=1 ) {
            document.write("<tr><td>");
            document.write(x[i].getAttribute('Name'));
            document.write("</td><td>");
            document.write( y[n].childNodes[0].nodeValue );
            document.write("</td></tr>");
        }
    }
    document.write("</table>");
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM