How to Parse XML in JavaScript (With Examples)
TutorialsLearn how to effectively parse XML with JavaScript. Enhance your development skills and tackle XML data with confidence.

Eugenijus Denisov
Key Takeaways
-
Use DOMParser in the browser for quick, native XML-to-DOM conversion - ideal for small XML inputs.
-
Use xml2js or fast-xml-parser in Node.js to convert XML to JavaScript objects for easier manipulation.
-
Choose tools based on context: native APIs for simplicity, third-party tools for large files, performance, or JSON conversion.
XML stands for eXtensible Markup Language. It provides a structured method for storing and transporting data. Even when we have formats like JSON, XML remains useful today, as it appears in many places where systems are only capable of parsing XML, such as old databases, APIs, configuration files, and especially RSS feeds.
If you deal with XML documents often, knowing how to parse XML correctly will help you avoid bugs and keep your XML data cleaner and usable.
Understanding XML Parsing in JavaScript
To parse XML, you take a raw string and turn it into a format that JavaScript can work with. That’s usually a DOM tree or a JavaScript object.
Parsing creates a tree-like structure, allowing you to read values, change data, or extract information from your XML document.
Parsing Methods Depend on Environment
The tools depend on where your JavaScript runs:
- In the browser
Use DOMParser or .responseXML.
- In Node.js
Use packages like xml2js or fast-xml-parser.
They all help you parse XML, but they do it differently. Choose the one that suits your setup best.
Why It’s Different From JSON
JavaScript has no built-in XML.parse() equivalent to JSON.parse(). Instead, you need to use tools like DOMParser in the browser or third-party libraries in Node.js to handle XML data.
It makes XML parsing a bit more challenging as you’ll need to use a proper XML parser to read and work with the XML data.
Parsing XML in the Browser
To parse XML in the browser, DOMParser is the primary tool of choice. You create a new DOMParser, feed it an XML string, and get a DOM tree back. It looks like this:
const xml = `<note><to>User</to><from>Admin</from></note>`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xml, "application/xml");
console.log(xmlDoc);
To run the code in a browser, press F12 and navigate to the Console. You may need to type in “allow pasting” to paste code into the console. If it executed correctly, you should be able to click on the “document” output to get the XML file.
You now have a clean XML document. If something breaks, you can check for parsing errors like this:
if (xmlDoc.getElementsByTagName("parsererror").length > 0) {
console.error("Malformed XML");
}
To get data, use .getElementsByTagName() or .querySelector() to walk the DOM tree. For example:
const toElements = xmlDoc.getElementsByTagName('to');
toElements[0].textContent;
Fetching Remote XML Files
If you want to parse XML data from a URL, you can fetch remote XML files using this:
fetch("https://example.com/feed.xml")
.then(res => res.text())
.then(xmlText => {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlText, "application/xml");
console.log(xmlDoc);
});
It works well with RSS feeds or remote config files. Just remember to handle errors and use a new DOMParser for every parse.
Using XMLHttpRequest (Legacy)
This method is outdated, but some developers still use it in legacy systems:
const xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);
xhr.onload = function () {
const xmlDoc = xhr.responseXML;
console.log(xmlDoc);
};
xhr.send();
.responseXML gives you a DOM tree directly. You’ll see this in older codebases, but generally you should avoid using it for new projects unless there’s no other way around it.
Note that it runs a GET request, so the “data.xml” file should be available on the website for the code to work. Otherwise, it’ll return 404.
Parsing XML in Node.js
xml2js is a popular tool for parsing XML and converting it into a JavaScript object. Start by installing xml2js with npm:
npm install xml2js
const { parseString } = require("xml2js");
const xml = `<note><to>User</to></note>`;
parseString(xml, (err, result) => {
if (err) throw err;
console.log(result);
});
To run the code, open the terminal in your IDE and type in:
node file_name.js
It’s perfect for fast dev tasks or reading a small XML file. You can easily convert the structure and work with the data just like JSON.
Using fast-xml-parser
fast-xml-parser is fast, lightweight, and also works in the browser. It’s often recommended over xml2js. You’ll need to install with npm as well:
npm install fast-xml-parser
We’ll now need to set up code that includes fast-xml-parser. It looks like this:
const { XMLParser } = require("fast-xml-parser");
const xml = `<note><to>User</to></note>`;
const parser = new XMLParser();
const result = parser.parse(xml);
console.log(result);
You can also tweak options for attribute handling, ignoring namespaces, and more. You’ll simply need to create an options constant and send it as an argument to the parser:
const options = { ignoreAttributes: false, attributeNamePrefix: "@_" };
const parser = new XMLParser(options);
Use fast-xml-parser when you need speed and clean output. It handles large XML strings efficiently. However, for true streaming, you may want to consider a library like SAX.
Other Tools: xmldom, @rgrove/parse-xml
If you want to work with the DOM tree in Node.js, use xmldom or @rgrove/parse-xml. You’ll need to run npm install for either:
const { DOMParser } = require('xmldom');
const xml = `<note><to>User</to></note>`;
const xmlDoc = new DOMParser().parseFromString(xml, "application/xml");
These tools help you simulate browser-like parsing with a new DOMParser-like interface.
Handling Edge Cases & Large XML Files
When you parse XML, always check for malformed tags or broken structure. Bad XML happens, and you must notice it when it does.
Namespaces can cause confusion, so it’s best to use an XML parser that respects them, such as fast-xml-parser with the correct configuration or DOM-based parsers.
For large XML files, avoid loading everything at once. Use these strategies:
- Streaming parsers (like SAX).
- Breaking the file into smaller parts.
- Offloading parsing to other services.
This way, you should avoid running out of memory.
Best Practices for XML Parsing
To have the best experience with XML parsing, we recommend that you follow these best practices:
- Validate every XML file before you parse XML.
- Use tools made for your environment: DOMParser for browsers, fast-xml-parser or xml2js for Node.
- Don’t bring in big libraries if your job is small.
- Handle errors with care and always check output after parsing.
Quick Recap
To sum up, here’s a brief overview of when to use which tool:
1. DOMParser is best for browsers and gives a DOM tree from an XML string.
2. xml2js is great for converting XML data to a JavaScript object, which is ideal for most small XML datasets.
3. fast-xml-parser has excellent speed, works well with small XML files, and supports more features.
Choose the tool that answers your needs the best, and you’ll be on your way to finishing your parsing projects in XML documents quickly and efficiently.
FAQ
Can JavaScript parse XML attributes and elements differently?
Yes, tools like fast-xml-parser let you choose how to handle attributes separately from elements using options.
How do I handle XML namespaces in JavaScript?
Use an XML parser that supports namespaces. fast-xml-parser has specific settings for that, but DOM-based parsers are generally more convenient for that.
Is it possible to convert XML to JSON in the browser?
Yes, use DOMParser to get a DOM tree, then write logic to convert it into a JavaScript object.
How do I preserve the order of XML tags when parsing?
Most parsers keep the order by default. Check parser settings to be sure.
How do I diagnose and fix parsing errors with DOMParser?
Check for a <parsererror> node in the returned DOM tree after using a new DOMParser.