The Wayback Machine - https://web.archive.org/web/20240620150032/https://www.geeksforgeeks.org/how-to-loop-through-xml-in-javascript/
Open In App

How to Loop through XML in JavaScript ?

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, looping over XML data is important for processing and extracting information from structured XML documents.

Below is a list of methods utilized to loop through XML.

Using for loop with DOMParser and getElementsByTagName

In this approach, we are using a DOMParser from the xmldom module to parse the XML data into a document object. Then, we use getElementsByTagName to select all elements with the tag name ‘language‘ and iterate through them using a for loop, accessing child elements within each ‘language‘ element to retrieve and display their content.

Run the below command to install xmldom before running the code:

npm install xmldom

Example: The below example uses for loop with DOMParser and getElementsByTagName To Loop Through XML in JavaScript.

JavaScript
let DOMParser = require('xmldom').DOMParser;
const xmlData = `
<languages>
    <language>
        <name>JavaScript</name>
        <type>Programming</type>
    </language>
    <language>
        <name>Python</name>
        <type>Programming</type>
    </language>
    <language>
        <name>Java</name>
        <type>Programming</type>
    </language>
</languages>
`;
const parser = new DOMParser();
const xmlDoc = parser.
    parseFromString(xmlData, 'text/xml');
const lNodes = xmlDoc.
    getElementsByTagName('language');
for (let i = 0; i < lNodes.length; i++) {
    const name = lNodes[i].
        getElementsByTagName('name')[0].textContent;
    const type = lNodes[i].
        getElementsByTagName('type')[0].textContent;
    console.log(`Name: ${name}, Type: ${type}`);
}

Output:

Name: JavaScript, Type: Programming
Name: Python, Type: Programming
Name: Java, Type: Programming

Using Array.from with DOMParser and childNodes

In this approach, we are using Array.from to convert the NodeList into an array, allowing us to use forEach for iteration. Within the forEach loop, we check if each node is an element node with the name ‘language‘ before extracting and displaying the content of its child elements (‘name‘ and ‘type‘).

Run the below command to install xmldom before running the code:

npm install xmldom

Example: The below example uses Array.from with DOMParser and childNodes To Loop Through XML in JavaScript.

JavaScript
const {
    DOMParser
} = require('xmldom');
const xmlData = `
<languages>
    <language>
        <name>JavaScript</name>
        <type>Programming</type>
    </language>
    <language>
        <name>Python</name>
        <type>Programming</type>
    </language>
    <language>
        <name>Java</name>
        <type>Programming</type>
    </language>
</languages>
`;
const parser = new DOMParser();
const xmlDoc = parser.
    parseFromString(xmlData, 'text/xml');
const lNodes = xmlDoc.
    documentElement.childNodes;
Array.from(lNodes).forEach(node => {
    if (node.nodeType === node.ELEMENT_NODE && 
            node.nodeName === 'language') {
        const name = node.
            getElementsByTagName('name')[0].textContent;
        const type = node.
            getElementsByTagName('type')[0].textContent;
        console.log(`Name: ${name}, Type: ${type}`);
    }
});

Output:

Name: JavaScript, Type: Programming
Name: Python, Type: Programming
Name: Java, Type: Programming


Similar Reads

How to loop through HTML elements without using forEach() loop in JavaScript ?
In this article, we will learn how to loop through HTML elements without using the forEach() method. This can be done in the following ways: Table of Content Approach 1: Using the for loopApproach 2: Using the While loopApproach 3: Using the 'for.....of' statementApproach 4: Using the for...in statementApproach 1: Using the for loopThe HTML element
4 min read
How to Loop Through an Array using a foreach Loop in PHP?
Given an array (indexed or associative), the task is to loop through the array using foreach loop. The foreach loop iterates through each array element and performs the operations. PHP foreach LoopThe foreach loop iterates over each key/value pair in an array. This loop is mainly useful for iterating through associative arrays where you need both t
2 min read
How to loop through a plain object with the objects as members in JavaScript ?
Looping through a plain JavaScript object with objects as members means iterating over each property of the object and accessing its values, which may also be objects. This is a common task in JavaScript, especially when dealing with JSON data or APIs. There are several ways to loop through a plain JavaScript object with objects as members. Here ar
3 min read
What is the fastest way to loop through an array in JavaScript ?
The fastest way to loop through an array in JavaScript depends upon the usecases and requirements. JavaScript has a large variety of loops available for performing iterations. The following loops along with their syntax are supported by JavaScript. Table of Content for loop while loop .forEach() loopfor...of Loopfor loop A JavaScript for loop compr
3 min read
How to loop through an array containing multiple objects and access their properties in JavaScript ?
Looping through an array of elements is straightforward because you can access them using their indexes. However, it's a bit different with objects since they consist of key-value pairs, and you can't index them like an array. To loop through an array of objects in JavaScript, you need to use different methods compared to traditional arrays. JavaSc
4 min read
How to use loop through an array in JavaScript ?
Looping through arrays in JavaScript is a fundamental operation, essential for data manipulation, iteration, and applying functions to elements. This guide covers efficient methods to loop through arrays, enhancing your coding skills. JavaScript offers several methods to traverse through arrays, each with its unique characteristics and use-cases. L
3 min read
How to loop through a list of elements and display it in VueJS ?
Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. The v-for directive is used to loop o
2 min read
How to loop through input elements in jQuery ?
In this article, we will learn how to loop through input elements and display their current values in jQuery. This can be done using two approaches: Approach 1: In this approach, we will iterate over every input type which is of text type by using input[type=text] as the selector. Next, we will use the each() method to iterate over the inputs to di
2 min read
How to Loop through Object with *ngFor in Angular ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will learn Loop through Object with *ngFor in Angular. Table of Content Steps for Installing &amp; Configuring the Angular ApplicationProject StructureUsing PipeUsing
3 min read
How to Loop through array of JSON object with *ngFor in Angular ?
JavaScript Object Notation (JSON) is a text-based, human-readable interchange format used for representing simple data structures and objects in web browser-based code. In order to Loop through an array of JSON objects, the *ngFor directive can be utilized that helps to dynamically generate HTML content based on the data in those objects. For insta
3 min read