好的,我有以下html文件:
<!DOCTYPE html>
<html>
<style>
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
th,
td {
padding: 5px;
}
</style>
<body>
<button type="button" onclick="loadDoc()">Get the names</button>
<br>
<br>
<table id="demo"></table>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
xhttp.open("GET", "names.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table = "<tr><th>Names</th></tr>";
var x = xmlDoc.getElementsByTagName("Names");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
以下包含名称的xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<Names>
<Name>Alex</Name>
<Name>Anna</Name>
<Name>Eva</Name>
<Name>George</Name>
<Name>Jason</Name>
<Name>John</Name>
<Name>Lisa</Name>
<Name>Mary</Name>
<Name>Michael</Name>
<Name>Nick</Name>
<Name>Vicky</Name>
</Names>
我想要的是以某种方式从xml文件中取出名称并将它们存储在数组中然后打印出来。但由于某种原因,只有第一个名称存储正确(“Alex”)。我不明白我的意思做错了。有人帮帮我吗?我打赌myFunction(xml)
有问题,但我无法找到/修复它
答案 0 :(得分:2)
只有一个Names
标记,因此您的循环只会执行一次
我会循环遍历Name
标签。
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table = "<tr><th>Names</th></tr>";
var x = xmlDoc.getElementsByTagName("Name");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].childNodes[0].nodeValue;
}
document.getElementById("demo").innerHTML = table;
}
答案 1 :(得分:1)
你需要检查一下:
var x = xmlDoc.getElementsByTagName("Names"); // Get the Names node.
var data = x[0].getElementsByTagName("Name"); // Get the Name node.
(function() {
function myFunction(xml) {
var i;
var xmlDoc = (new window.DOMParser()).parseFromString(xml, "text/xml");
var table = "<tr><th>Names</th></tr>";
var x = xmlDoc.getElementsByTagName("Names");
var data = x[0].getElementsByTagName("Name");
for (i = 0; i < data.length; i++) {
table += "<tr><td>" + data[i].childNodes[0].nodeValue + "</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Names> <Name>Alex</Name> <Name>Anna</Name> <Name>Eva</Name> <Name>George</Name> <Name>Jason</Name> <Name>John</Name> <Name>Lisa</Name> <Name>Mary</Name> <Name>Michael</Name> <Name>Nick</Name> <Name>Vicky</Name></Names>";
myFunction(xml);
})();
&#13;
<table id="demo"></table>
&#13;