XML in HTML
Displaying XML Data in HTML using JavaScript
Section titled “Displaying XML Data in HTML using JavaScript”A common task is to fetch XML data and display it dynamically within an HTML page. Modern JavaScript provides efficient ways to achieve this.
In this example, we’ll fetch an XML file (cd_catalog.xml) containing a list of music CDs. We’ll then parse the XML and display the Artist and Title for each CD in an HTML table.
Assume cd_catalog.xml looks something like this:
<CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <YEAR>1985</YEAR> </CD> <CD> <TITLE>Hide your heart</TITLE> <ARTIST>Bonnie Tyler</ARTIST> <YEAR>1988</YEAR> </CD> ...</CATALOG>Here’s the HTML and JavaScript code:
<!DOCTYPE html><html><head><title>XML to HTML Example</title><style> table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 8px; text-align: left; } th { background-color: #f2f2f2; }</style></head><body>
<h1>CD Catalog</h1><table id="cdTable"> <thead> <tr> <th>Artist</th> <th>Title</th> </tr> </thead> <tbody> <!-- CD data will be inserted here by JavaScript --> </tbody></table>
<script> // Function to fetch and display XML data async function displayCatalog() { const tableBody = document.querySelector("#cdTable tbody"); tableBody.innerHTML = ''; // Clear existing table content
try { // 1. Fetch the XML file const response = await fetch('cd_catalog.xml'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const xmlText = await response.text();
// 2. Parse the XML string const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlText, "application/xml");
// Check for parsing errors (optional but recommended) const parseError = xmlDoc.querySelector('parsererror'); if (parseError) { console.error('Error parsing XML:', parseError); tableBody.innerHTML = '<tr><td colspan="2">Error loading or parsing XML data.</td></tr>'; return; }
// 3. Select all CD elements const cds = xmlDoc.querySelectorAll("CD"); // Using querySelectorAll for modern selection
// 4. Iterate through each CD element cds.forEach(cd => { // Get ARTIST and TITLE values (using nullish coalescing for safety) const artist = cd.querySelector("ARTIST")?.textContent ?? 'N/A'; const title = cd.querySelector("TITLE")?.textContent ?? 'N/A';
// 5. Create new table row and cells const row = document.createElement("tr");
const artistCell = document.createElement("td"); artistCell.textContent = artist; row.appendChild(artistCell);
const titleCell = document.createElement("td"); titleCell.textContent = title; row.appendChild(titleCell);
// 6. Append the row to the table body tableBody.appendChild(row); });
} catch (error) { console.error('Failed to load or process CD catalog:', error); tableBody.innerHTML = `<tr><td colspan="2">Failed to load data: ${error.message}</td></tr>`; } }
// Call the function when the page loads document.addEventListener('DOMContentLoaded', displayCatalog);
</script>
</body></html>This modern approach uses:
fetchAPI: For making asynchronous network requests (replacingXMLHttpRequest).async/await: To handle asynchronous operations more cleanly.DOMParser: The standard browser API for parsing XML (and HTML) strings into a DOM structure.- Standard DOM manipulation (
querySelector,querySelectorAll,createElement,appendChild,textContent): To safely and efficiently build the HTML table (replacingdocument.write). - Error handling (
try...catch): To manage potential issues during fetching or parsing.
For more advanced XML manipulation in JavaScript, explore the XML DOM (Document Object Model) interfaces further.