How to Parse XML in JavaScript
Advertisement
Ad
Parsing XML in JavaScript
JavaScript has a built-in DOMParser to read XML in the browser, and libraries for Node.js.
Browser: DOMParser
const xmlString = `<book><title>Clean Code</title></book>`;
const parser = new DOMParser();
const doc = parser.parseFromString(xmlString, "application/xml");
const title = doc.querySelector("title").textContent;
console.log(title); // "Clean Code"
Fetching and Parsing XML
const res = await fetch("/feed.xml");
const text = await res.text();
const doc = new DOMParser().parseFromString(text, "application/xml");
doc.querySelectorAll("item").forEach(item => {
console.log(item.querySelector("title").textContent);
});
Node.js: Use a Library
// npm install fast-xml-parser
const { XMLParser } = require("fast-xml-parser");
const parser = new XMLParser();
const obj = parser.parse(xmlString);
console.log(obj.book.title);
FAQs
How do I check for parse errors?
Look for a <parsererror> element in the parsed document. More in our XML section.
XML or JSON for new APIs?
JSON — it's native to JavaScript and simpler.
