In JavaScript, you can use async await to fetch data from external (or remote) files. Not just XML, you can extract and read JSON data using async and await.
Now lets see how we can read data from xml file using async and await.
Here’s the xml file from where we’ll extract the data for the table.
The Markup
We’ll add few elements to display the data. Also, add CSS for the table. Although, the table will be created using JavaScript dynamically.
<!DOCTYPE html>
<html>
<head>
<style>
th, td, p, input, h2 {
font-family: Calibri;
}
th, td, p, input {
font-size: 18px;
}
table, th, td {
border: solid 1px #ddd;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight:bold;
}
</style>
</head>
<body>
<input type='button' onclick='get_data()' value='Create Table using XML Data' />
<p id='showData'></p>
</body>
The Script
<script> // using async and await to fetch xml data. let get_data = async() => { let url = "../../library/library.xml"; // the XML file. let response = await fetch (url); const xmlData = await response.text().then(( str ) => { return new DOMParser().parseFromString(str, 'application/xml'); }); createTable(xmlData); // convert data to table. } let createTable = (xml) => { // the xml tag name let ucBooks = xml.getElementsByTagName('List'); let arr = []; for (let i = 0; i < ucBooks.length; i++) { // Push XML attributes into the array. arr.push({ Code: ucBooks[i].getElementsByTagName('code'), Name: ucBooks[i].getElementsByTagName('BookName'), Category: ucBooks[i].getElementsByTagName('Category'), Price: ucBooks[i].getElementsByTagName('Price') }); } let col = []; for (let i = 0; i < arr.length; i++) { for (let key in arr[i]) { if (col.indexOf(key) === -1) { col.push(key); } } } // Create a table. const table = document.createElement("table"); // Create table header row using the extracted headers above. let tr = table.insertRow(-1); // table row. for (let i = 0; i < col.length; i++) { let th = document.createElement('th'); // table header. th.innerHTML = col[i]; tr.appendChild(th); } // add data to the table as rows. for (let i = 0; i < arr.length; i++) { tr = table.insertRow(-1); for (let j = 0; j < col.length; j++) { let tabCell = tr.insertCell(-1); tabCell.innerHTML = arr[i][col[j]][0].childNodes[0].nodeValue; } } // Now, add the newly created table to a container. const result = document.getElementById('showData'); result.innerHTML = ""; result.appendChild(table); } </script> </html>
The method is very simple. If you are new to async and await, then please see this post.
One of the advantages of using this method is that the entire operation is done asynchronously.
Also, pay attention to how XML data is pushed (stored) in an array for later use.