Reputation: 117
I found one code on w3school which should display xml file in table format. I'm trying to make this work with my file, but I can't get it.
My code:
<!DOCTYPE html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<button type="button" onclick="loadXMLDoc()">Get my CD collection</button>
<br><br>
<table id="demo"></table>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "https://newfmplayer.online/AirPlayHistory.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>name</th><th>Song title</th></tr>";
var x = xmlDoc.getElementsByTagName("Song");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("Song title")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
Link to my file : https://newfmplayer.online/AirPlayHistory.xml Original code from w3schools : https://www.w3schools.com/xml/tryit.asp?filename=tryxml_display_table
Upvotes: 0
Views: 150
Reputation: 798
Well, actually in your xml file, attributes contain values. In w3school example, node itself contain values. So, basically you need to access node attributes, not the node (element) itself.
Follow This link on w3school to access attributes:
Example:
<!DOCTYPE html>
<html>
<head>
<title>Testing XMLHttpRequest</title>
<style type="text/css">
table,th,td {border : 1px solid black; border-collapse: collapse; }
th,td { padding: 5px; }
</style>
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "AirPlayHistory.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table = "<tr><th>name</th><th>Song title</th></tr>";
var songTitles = xmlDoc.getElementsByTagName("Song");
var artistNames = xmlDoc.getElementsByTagName("Artist");
for (i = 0; i < songTitles.length; i++) {
table += "<tr><td>" + artistNames[i].attributes.getNamedItem("name").nodeValue + "</td><td>" +
songTitles[i].attributes.getNamedItem("title").nodeValue + "</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</head>
<body>
<button type="button" onclick="loadXMLDoc()">Get my CD collection</button>
<br/><br/>
<table id="demo"></table>
</body>
</html>
Upvotes: 1