Skip to content

XML Application

This section demonstrates basic examples of how XML data can be fetched, parsed, and displayed in a web page using JavaScript and the XML DOM.

Modern web development often uses JSON for data exchange due to its simpler integration with JavaScript, but understanding how to process XML remains valuable, especially when interacting with legacy systems, web services (SOAP), or specific XML-based formats (like RSS, SVG).

Let’s assume we have an XML file (catalog.xml) with the following structure:

<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
<!-- ... more CD elements ... -->
</CATALOG>

Modern JavaScript uses the fetch API to retrieve resources and the DOMParser API to parse XML text into a DOM object.

async function loadCatalog() {
try {
const response = await fetch('catalog.xml');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const xmlText = await response.text();
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlText, "application/xml");
// Now you can work with the xmlDoc object
displayFirstCD(xmlDoc);
setupNavigation(xmlDoc);
} catch (error) {
console.error('Error loading or parsing XML:', error);
document.getElementById('showCD').innerHTML = 'Failed to load catalog.';
}
}
// Call this function when the page loads, e.g.:
// window.addEventListener('load', loadCatalog);

Note: The older XMLHttpRequest object can also be used but fetch is generally preferred.

This function extracts data from the first <CD> element in the parsed xmlDoc and displays it in an HTML element (e.g., <div id="showCD"></div>).

function displayCD(xmlDoc, index) {
const cds = xmlDoc.getElementsByTagName("CD");
if (index < 0 || index >= cds.length) {
console.error("Index out of bounds");
return;
}
const cd = cds[index];
// Using textContent for safer and easier text extraction
const title = cd.getElementsByTagName("TITLE")[0]?.textContent ?? 'N/A';
const artist = cd.getElementsByTagName("ARTIST")[0]?.textContent ?? 'N/A';
const year = cd.getElementsByTagName("YEAR")[0]?.textContent ?? 'N/A';
const displayText = `
**Artist:** ${artist}<br>
**Title:** ${title}<br>
**Year:** ${year}
`;
document.getElementById("showCD").innerHTML = displayText;
}
function displayFirstCD(xmlDoc) {
displayCD(xmlDoc, 0);
}

The ?. (optional chaining) and ?? (nullish coalescing) operators provide robustness against missing elements or text content.

To allow users to cycle through the CDs, you can add ‘Next’ and ‘Previous’ buttons and corresponding functions.

let currentCDIndex = 0;
let catalogXmlDoc = null; // Store the parsed document
function setupNavigation(xmlDoc) {
catalogXmlDoc = xmlDoc; // Store for later use
const cds = catalogXmlDoc.getElementsByTagName("CD");
document.getElementById('prevButton').addEventListener('click', () => {
if (currentCDIndex > 0) {
currentCDIndex--;
displayCD(catalogXmlDoc, currentCDIndex);
}
});
document.getElementById('nextButton').addEventListener('click', () => {
if (currentCDIndex < cds.length - 1) {
currentCDIndex++;
displayCD(catalogXmlDoc, currentCDIndex);
}
});
// Initial display
displayCD(catalogXmlDoc, currentCDIndex);
}
// Make sure you have <button id="prevButton">Previous</button>
// and <button id="nextButton">Next</button> in your HTML.

This basic structure illustrates fetching, parsing, and interacting with XML data in a web context. For more complex interactions, exploring libraries or frameworks that abstract DOM manipulation might be beneficial.

Further study of the XML DOM API and JavaScript’s interaction with it will allow for more sophisticated applications.