XML Parser
Before a program can work with XML data, it must first turn the raw text into a structure the language can navigate — that is the job of an XML parser.
What an XML Parser Does
An XML parser reads a stream of characters — the raw text of an XML document — and converts it into an in-memory structure of nodes: elements, attributes, text, and comments, connected in a tree. This structure is what programming languages actually interact with; nothing works directly on the raw string of angle brackets and text. Every browser ships with a built-in XML parser, and virtually every programming language provides an XML parsing library.
Parsing happens in two broad ways. A validating parser checks the document against a schema or DTD and rejects it if the structure doesn't match the rules. A non-validating parser only checks that the document is well-formed — correctly nested tags, one root element, properly closed quotes on attributes — without checking it against any external rule set.
DOMParser in JavaScript
In the browser, the DOMParser object turns a string of XML text into a Document object, which is then explored using the same DOM methods used on HTML. This is the standard way to parse XML that arrives as text — for example, from a fetch() response, a form textarea, or a hardcoded string in your script.
Parsing an XML string into a Document using DOMParser.
Basic DOMParser usage
<!DOCTYPE html>
<html>
<body>
<script>
const xmlText = `<note>
<to>Alex</to>
<from>Sam</from>
<message>Meeting moved to 3pm</message>
</note>`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlText, "text/xml");
console.log(xmlDoc.getElementsByTagName("message")[0].textContent);
// "Meeting moved to 3pm"
</script>
</body>
</html>Detecting a parse error when the XML is not well-formed.
Checking for parser errors
<!DOCTYPE html>
<html>
<body>
<script>
const badXml = "<note><to>Alex</note>"; // missing closing </to>
const parser = new DOMParser();
const doc = parser.parseFromString(badXml, "text/xml");
const errorNode = doc.getElementsByTagName("parsererror")[0];
if (errorNode) {
console.log("Parsing failed:", errorNode.textContent);
} else {
console.log("Document parsed successfully.");
}
</script>
</body>
</html>Parsing XML fetched over the network before reading its content.
Fetching and parsing XML from a URL
<!DOCTYPE html>
<html>
<body>
<script>
fetch("data/books.xml")
.then(response => response.text())
.then(str => new DOMParser().parseFromString(str, "text/xml"))
.then(xmlDoc => {
const titles = xmlDoc.getElementsByTagName("title");
for (const el of titles) {
console.log(el.textContent);
}
});
</script>
</body>
</html>Exercise: XML Parser
What is the fundamental job of an XML parser?