Today we will figure out how to work with XML in JavaScript. If XML sounds like something incomprehensible, don't worry! We will analyze everything in great detail, and also add more examples to make everything as clear as possible.
XML (along with HTML) is one of the formats for storing data, they look similar to HTML. Let's figure out how to analyze and display them using JavaScript.

What is XML?
XML (eXtensible Markup Language) is a text format for storing and transmitting data. It looks like this:
<люди>
<человек>
<имя>Иван</имя>
<возраст>25</возраст>
</человек>
<человек>
<имя>Мария</имя>
<возраст>30</возраст>
</человек>
</люди>Here we have "people" that contain several "people" with their "name" and "age". It's like a table in text form.
Now, let's learn how to parse such XML using JavaScript.
How to parse XML with JavaScript?
There are several steps that will help you work with XML:
Get XML data: data can be taken from the server or simply stored as a string in JavaScript.
Convert them to an object: to work with XML, we need to convert it into an object that JavaScript can work with.
Extract data: after that, you can extract specific values.
Let's start with the simplest example.
Example 1: Parsing a simple XML string
Let's say we have a string with XML:
const xmlString = `
<person>
<person>
<name>Ivan</name>
<age>25</age>
</person>
<person>
<name>Maria</name>
<age>30</age>
</person>
</people>`;Now we need to convert it into an object. JavaScript has a built-in object for this DOMParser.
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");Now xmlDoc is an object that you can work with.
Extracting data from XML
To extract data, we need to refer to XML nodes as HTML elements. We use the method getElementsByTagName():
const people = xmlDoc.getElementsByTagName("people");
for (let i = 0; i < people.length; i++) {
const name = people[i].getElementsByTagName("name")[0].textContent;
const age = people[i].getElementsByTagName("age")[0].textContent;
console.log(`Name: ${name}, Age: ${age}`);
}Here we go through each "person" and get their "name" and "age". As a result, the console will display:
Имя: Иван, Возраст: 25
Имя: Мария, Возраст: 30Example 2: Parsing XML from an HTML document
Sometimes XML can be part of a web page, and we need to parse it right from there. Let's imagine that our HTML has the following element:
<div id="xml">
<люди>
<человек>
<имя>Сергей</имя>
<возраст>28</возраст>
</человек>
<человек>
<имя>Ольга</имя>
<возраст>34</возраст>
</человек>
</люди>
</div>To get this XML and analyze it, we can do this:
const xmlStringFromHtml = document.getElementById("xml").innerHTML;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlStringFromHtml, "text/xml");
const люди = xmlDoc.getElementsByTagName("people");
for (let i = 0; i < people.length; i++) {
const name = people[i].getElementsByTagName("name")[0].textContent;
const age = people[i].getElementsByTagName("age")[0].textContent;
console.log(`Name: ${name}, Age: ${age}`);
}Here we first take the HTML content and then use it as XML.
Example 3: Error handling
Sometimes XML can be incorrect, and we need to be able to handle it. For example, if the tag is not closed, it may cause an error. To process it, you can add a check:
const invalidXmlString = `<person> <name>Ivan</name> <age>25</age></person>`; // Error: <people> not closed
try {
const xmlDoc = parser.parseFromString(invalidXmlString, "text/xml");
const ошибка = xmlDoc.getElementsByTagName("parsererror");
if (ошибка.length > 0) {
console.error("XML error:", ошибка[0].textContent);
} else {
console.log("XML is correct");
}
} catch (e) {
console.error("Error parsing XML:", e);
}Results
That's it! We have learned:
Parse XML strings in JavaScript.
Extract data from XML using methods similar to working with HTML.
Process errors in XML.
XML is a fairly old but still useful format for data exchange. Now you know how to work with it using JavaScript! 🎉
If you have any questions or want more examples, write to me, I will be happy to help! 😊
