How to use Array.from with DOMParser and childNodes In Javascript
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.
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
How to Loop through XML in JavaScript ?
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.
Table of Content
- Using for loop with DOMParser and getElementsByTagName
- Using Array.from with DOMParser and childNodes