I have come across a problem while fetching data from an external XML document with JS. I have been following the w3schools tutorial for AJAX XML so far, but I ran into something I couldn’t solve. I have a XML that looks like this:
JavaScript
x
16
16
1
<root>
2
<document-id>
3
<author>Tom Riddle</autor>
4
<title>abzy</title>
5
<year>1995</year>
6
</document-id>
7
<document-id>
8
<author>Tom Riddle</autor>
9
<title>abzy</title>
10
</document-id>
11
<document-id>
12
<author>Tom Riddle</autor>
13
<year>1995</year>
14
</document-id>
15
</root>
16
I want to dynamically access the data inside the XML and create a table while doing so. It works fine for the one DOM Element all documents share, but it gives me an error as soon as I include year or title. I guess it’s because the tags are empty in some parts of the tree. Is there a way to ignore empty tags and only write something in the column if there is a value inside? Thank you for your time and knowledge.
THIS IS THE ASSOCIATED HTML
JavaScript
1
41
41
1
<body>
2
<header>
3
<h1>Reading Data from XML Files</h1>
4
</header>
5
<main>
6
7
<button type="button" onclick="loadDoc()">Get my CD collection</button>
8
9
<table id="demo">
10
11
</table>
12
13
</main>
14
<script>
15
function loadDoc() {
16
const xhttp = new XMLHttpRequest();
17
xhttp.onload = function() {
18
myFunction(this);
19
}
20
xhttp.open("GET", "books.xml");
21
xhttp.send();
22
}
23
function myFunction(xml) {
24
const xmlDoc = xml.responseXML;
25
const x = xmlDoc.getElementsByTagName("document-id");
26
console.log(x)
27
let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>";
28
for (let i = 0; i <x.length; i++) {
29
table += "<tr><td>" +
30
x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
31
"</td><td>" +
32
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
33
"</td><td>" +
34
x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue +
35
"</tr>";
36
}
37
document.getElementById("demo").innerHTML = table;
38
}
39
</script>
40
</body>
41
Advertisement
Answer
try this with in line solution to check if tag exist in xml
JavaScript
1
18
18
1
function myFunction(xml) {
2
const xmlDoc = xml.responseXML;
3
const x = xmlDoc.getElementsByTagName("document-id");
4
console.log(x)
5
let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>";
6
7
for (let i = 0; i <x.length; i++) {
8
table += "<tr><td>" +
9
x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
10
"</td><td>" + ((x[i].getElementsByTagName("title")[0] == undefined)?"": x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue ) +
11
"</td><td>" +
12
((x[i].getElementsByTagName("year")[0] == undefined)?"": x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue ) +
13
"</tr>";
14
}
15
16
document.getElementById("demo").innerHTML = table;
17
}
18