gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:00:20 25 4
gpt4 key购买 nike

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

我正在从 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>

关于javascript - 使用 HTML/JS 提取特定的 XML 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25511630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com