AJAX XML File
Working with XML Data (Legacy)
Section titled “Working with XML Data (Legacy)”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.
Fetching and Parsing XML Example
Section titled “Fetching and Parsing XML Example”This example shows how to fetch an XML file from the server and display its contents in an HTML table.
HTML Structure:
Section titled “HTML Structure:”<button id="loadXmlBtn">Load CD Catalog (XML)</button><div id="cdInfoContainer"></div>JavaScript (using Fetch and DOMParser):
Section titled “JavaScript (using Fetch and DOMParser):”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});Example Explained
Section titled “Example Explained”-
Event Listener: An event listener is attached to the button. When clicked, it calls the
loadXMLDatafunction. -
async function loadXMLData: This asynchronous function handles the entire process. -
Fetch API:
fetch(url)initiates the request to get the XML file. -
Error Handling: It checks
response.okfor HTTP errors and uses atry...catchblock for network or other runtime errors. -
Get Text:
response.text()reads the response body as a string. -
DOMParser:
new DOMParser()creates a parser instance.parser.parseFromString(xmlText, "application/xml")parses the XML string into an XML Document object. -
Parsing Error Check: It explicitly checks if the browser detected a parsing error within the resulting XML document.
-
Data Extraction:
xmlDoc.getElementsByTagName("CD")gets all CD elements. A loop iterates through them. -
DOM Traversal:
querySelectoris 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. -
HTML Generation: Template literals are used to build the HTML table string, which is cleaner than string concatenation.
-
Update UI:
cdInfoContainer.innerHTML = tableHTML;updates the page content.
The XML File Structure
Section titled “The XML File Structure”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.