Skip to content

AJAX XML File

While JSON is the preferred format for modern web APIs, you might occasionally need to interact with services that provide data in XML format. Modern JavaScript provides ways to handle this.

This section demonstrates fetching and parsing XML using the Fetch API and the browser’s built-in XML parsing capabilities.

This example shows how to fetch an XML file from the server and display its contents in an HTML table.

<button id="loadXmlBtn">Load CD Catalog (XML)</button>
<div id="cdInfoContainer"></div>
async function loadXMLData(url) {
const cdInfoContainer = document.getElementById('cdInfoContainer');
cdInfoContainer.innerHTML = 'Loading...'; // Provide user feedback
try {
const response = await fetch(url);
if (!response.ok) { // Check for HTTP errors (e.g., 404 Not Found)
throw new Error(`HTTP error! Status: ${response.status}`);
}
const xmlText = await response.text(); // Get response as text
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlText, "application/xml");
// Check for parsing errors
const parserError = xmlDoc.querySelector('parsererror');
if (parserError) {
console.error('XML Parsing Error:', parserError.textContent);
throw new Error('Failed to parse XML data.');
}
const cds = xmlDoc.getElementsByTagName("CD");
let tableHTML = `<table border='1'>
<thead>
<tr><th>Title</th><th>Artist</th></tr>
</thead>
<tbody>`;
for (let i = 0; i < cds.length; i++) {
const cd = cds[i];
// Use querySelector for safer node access and provide defaults
const titleNode = cd.querySelector("TITLE");
const artistNode = cd.querySelector("ARTIST");
const title = titleNode?.textContent || 'N/A'; // Optional chaining and default value
const artist = artistNode?.textContent || 'N/A';
tableHTML += `<tr><td>${title}</td><td>${artist}</td></tr>`;
}
tableHTML += `</tbody></table>`;
cdInfoContainer.innerHTML = tableHTML;
} catch (error) {
console.error('Error fetching or parsing XML:', error);
cdInfoContainer.innerHTML = `<p style="color: red;">Error loading data: ${error.message}</p>`;
}
}
document.getElementById('loadXmlBtn').addEventListener('click', () => {
loadXMLData('cd_catalog.xml'); // Assuming cd_catalog.xml is the XML file
});
  1. Event Listener: An event listener is attached to the button. When clicked, it calls the loadXMLData function.

  2. async function loadXMLData: This asynchronous function handles the entire process.

  3. Fetch API: fetch(url) initiates the request to get the XML file.

  4. Error Handling: It checks response.ok for HTTP errors and uses a try...catch block for network or other runtime errors.

  5. Get Text: response.text() reads the response body as a string.

  6. DOMParser: new DOMParser() creates a parser instance. parser.parseFromString(xmlText, "application/xml") parses the XML string into an XML Document object.

  7. Parsing Error Check: It explicitly checks if the browser detected a parsing error within the resulting XML document.

  8. Data Extraction: xmlDoc.getElementsByTagName("CD") gets all CD elements. A loop iterates through them.

  9. DOM Traversal: querySelector is used within each CD element to find TITLE and ARTIST elements. Optional chaining (?.) and default values (|| 'N/A') make the code more robust against missing XML nodes.

  10. HTML Generation: Template literals are used to build the HTML table string, which is cleaner than string concatenation.

  11. Update UI: cdInfoContainer.innerHTML = tableHTML; updates the page content.

The example assumes an XML file (cd_catalog.xml) with a structure similar to this:

<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>

Key Takeaway: Use fetch to get the data as text, then DOMParser to convert it into a usable XML document object for data extraction.