Skip to content

XML Parser

Modern web browsers have built-in capabilities to parse XML documents received from a server or defined as strings.

Parsing converts the text-based XML document into an XML Document Object Model (DOM) object. This DOM object represents the XML structure in memory, allowing you to access and manipulate its elements and attributes using JavaScript.

Parse an XML Document Fetched from a Server

Section titled “Parse an XML Document Fetched from a Server”

The modern approach to fetch resources, including XML files, from a server is using the fetch API with async/await syntax.

Here’s how you can fetch an XML file (data.xml) and parse it:

async function loadAndParseXML(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Get the response text
const xmlText = await response.text();
// Use DOMParser to parse the text
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);
throw new Error('Error parsing XML');
}
console.log("XML parsed successfully:", xmlDoc);
// Now you can work with the xmlDoc object
// Example: Get the root element's tag name
console.log("Root element:", xmlDoc.documentElement.tagName);
} catch (error) {
console.error('Could not fetch or parse XML:', error);
}
}
// Example usage:
loadAndParseXML('data.xml');

Note: The older XMLHttpRequest object can also fetch and parse XML (using responseXML), but fetch is preferred for its cleaner promise-based API. Avoid synchronous XMLHttpRequest as it blocks the browser.

If you have XML content as a string within your JavaScript code, you can parse it directly using DOMParser:

const xmlString = `
<bookstore>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
</book>
</bookstore>
`;
try {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "application/xml");
// Check for parsing errors
const parseError = xmlDoc.querySelector('parsererror');
if (parseError) {
console.error("Error parsing XML string:", parseError);
throw new Error('Error parsing XML string');
}
console.log("XML string parsed successfully:", xmlDoc);
// Access data, e.g., the book title
const title = xmlDoc.querySelector('book > title').textContent;
console.log("Book Title:", title); // Output: Learning XML
} catch (error) {
console.error('Could not parse XML string:', error);
}

The DOMParser interface is standard across all modern browsers. Obsolete methods like ActiveXObject("Microsoft.XMLDOM") for old Internet Explorer versions are no longer necessary.

For security reasons, web browsers enforce the Same-Origin Policy. This means a web page served from domain-a.com cannot directly fetch resources (like an XML file) from domain-b.com unless domain-b.com explicitly allows it.

This permission mechanism is called Cross-Origin Resource Sharing (CORS). If you need to fetch XML from a different domain, the server hosting the XML file must include appropriate CORS headers (like Access-Control-Allow-Origin) in its response.

If the web page and the XML file are served from the same origin (same protocol, domain, and port), you won’t encounter CORS issues.

Learn more about CORS on MDN

Once you have parsed the XML into an xmlDoc object, you can navigate and extract data using standard DOM methods similar to how you work with HTML DOM, such as getElementById, getElementsByTagName, querySelector, querySelectorAll, accessing textContent, attributes, etc.

The next chapter will delve deeper into accessing data from the XML DOM object.