XML结构如下,我试图将数据输出到HTML表中,但内部循环只返回null而不是Elements中的文本,我评论了我在JavaScript中遇到问题的部分
<playlist>
<id>PLnqdTIS_B64I7zbB_tPgvHiFTnmIqpT0u</id>
<title>Yanni Covers</title>
<numVideos>23</numVideos>
<video>
<id>Kg42VjNo0Pw</id>
<title>Yanni - Before I Go Piano Cover</title>
<duration>4:33</duration>
<thumbnail>http://i1.ytimg.com/vi/Kg42VjNo0Pw/1.jpg</thumbnail>
<datePublished>2014-04-29</datePublished>
<views>156</views>
<favorites>0</favorites>
<numRated>3</numRated>
<author>migoicons</author>
</video>
<video>
<id>CKtH0H416Zg</id>
<title>Yanni - Face In The Photograph</title>
<duration>4:20</duration>
<thumbnail>http://i1.ytimg.com/vi/CKtH0H416Zg/1.jpg</thumbnail>
<datePublished>2014-03-27</datePublished>
<views>562</views>
<favorites>0</favorites>
<numRated>13</numRated>
<author>migoicons</author>
</video>
</playlist>
JavaScript
var playlist = "";
function loadXML() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
playlist = xmlhttp.responseXML;
var html = "";
html += "<b>Playlist ID : </b>" + getNodeVal('id') + "<br />";
html += "<b>Playlist Title : </b>" + getNodeVal('title') + "<br />";
html += "<b>Playlist Description : </b>" + getNodeVal('description') + "<br />";
html += "<b>Playlist Videos : </b>" + getNodeVal('numVideos') + "<br />";
html += "<br /><strong>List of videos</strong> <br /><br />";
html += "<table><tr>\n\
<th>Index</th>";
for (var x = 0; x < getEBTN('video')[0].childNodes.length; x++) {
html += "<th>" +
getEBTN('video')[0].childNodes[x].tagName + " </th>";
}
html += "</tr>";
for (var a = 0; a < getEBTN('video').length; a++) {
html += "<tr><td>" + a + "</td>";
for (var y = 0; y < getEBTN('video')[0].childNodes.length; y++) {
/* can't get this part to work just getting null instead of text*/
html += "<td>" + getEBTN('video')[a].childNodes[y].nodeValue + "</td>";
}
html += "</tr>";
}
html += "</table>";
document.getElementById("myDiv").innerHTML = html;
}
}
xmlhttp.open("GET", "xml_server.php?id=nqdTIS_B64I7zbB_tPgvHiFTnmIqpT0u", true);
xmlhttp.send();
}
function getEBTN(tagName) {
return playlist.getElementsByTagName(tagName);
}
function getNodeVal(tagName) {
return getEBTN(tagName)[0].childNodes[0].nodeValue;
}
window.onload = loadXML;
答案 0 :(得分:1)
让我来解决这个问题:
getEBTN('video')
是视频元素的节点列表
getEBTN('video')[a]
是其中一个视频元素
getEBTN('video')[a].childNodes
是子元素的节点列表
getEBTN('video')[a].childNodes[y]
是一个子元素,例如<id>Kg42VjNo0Pw</id>
也就是说,元素没有nodeValue
(source)。
也许你想要getEBTN('video')[a].childNodes[y].textContent
。
答案 1 :(得分:0)
尝试在JavaScript中解析XML是一个特殊的地狱级别。