繁体   English   中英

如何使用 XML 数据动态填充 HTML 表?

[英]How to dynamically populate an HTML Table with XML Data?

我有一个 XML,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<TestRun id="abc-jhhg-yuh" name="Demo" runUser="Admin" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
 <ResultSummary outcome="Failed">
    <Counters total="5" executed="5" passed="3" failed="2" error="0" timeout="0" aborted="0" inconclusive="0" passedButRunAborted="0" notRunnable="0" notExecuted="0" disconnected="0" warning="0" completed="0" inProgress="0" pending="0" />
  </ResultSummary>
</TestRun>

我有一个 HTML 文件,我希望这些数据以表格格式动态填充,如下所示。

在此处输入图像描述

我在 HTML 中的“脚本”是这样的

<!DOCTYPE html>
<html>
<body>
<h1> Test Summary Details </h1> 
<script>
if(window.XMLHttpRequest)
{
    xmlhttp=new XMLHttpRequest();
}
else
{
    xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","Demo.xml",true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table border='1' width='25%' style='font-size:15px;'>");
document.write("<tr><th>Result Type</th><th>Count</th></tr>");
var nodes=xmlDoc.getElementsByTagName("ResultSummary");
var total= nodes[0].childNodes[0].getAttributeValue("total");
document.write("total");
document.write("</td><td>");
document.write(total);
document.write("</td><td>");
document.write("</table>");
</script>
</body>
</html>

但我无法填充数据。 我怎样才能做到这一点?

 // Simulate a http response const mock_response = new Response(`<?xml version="1.0" encoding="utf-8"?> <TestRun id="abc-jhhg-yuh" name="Demo" runUser="Admin" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010"> <ResultSummary outcome="Failed"> <Counters total="5" executed="5" passed="3" failed="2" error="0" timeout="0" aborted="0" inconclusive="0" passedButRunAborted="0" notRunnable="0" notExecuted="0" disconnected="0" warning="0" completed="0" inProgress="0" pending="0" /> </ResultSummary> </TestRun>`) // use the new fetch api instead of the old XMLHttpRequest // TODO: change url to 'Demo.xml' fetch('https://httpbin.org/get').then(async response => { // use the simulated response const str = await mock_response.text() // TODO: remove above and switch to use the actual response.text() instead // const str = await response.text() const xml = new DOMParser().parseFromString(str, 'text/xml') const counters = xml.querySelector('Counters') const table = document.createElement('table') table.border = 1 const body = table.createTBody() for (let x of 'total,executed,passed,failed,inconclusive,warning,notExecuted'.split(',')) { const row = body.insertRow() const attr = row.insertCell() const value = row.insertCell() attr.innerText = x value.innerText = counters.getAttribute(x) console.log() } document.body.append(table) })

暂无
暂无

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

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