How To Loop Through XML in JavaScript
When dealing with XML documents, a situation may arise where we need to parse and iterate through various text elements. Unfortunately, as a markup language, XML is quite unintuitive to iterate through.
This mainly due to the text in each element being a node that needs to be traversed through.
<name>Tommy Vercetti</name>
So, how can you loop through XML in JavaScript?
Well, we can traverse into the text node of each element to extract the text data in the following order:
- Traverse into the XML text node
- Create a text node with the text data in the DOM
- In order to do this, we can utilize nodeValue and createTextNode.
const getResponseXML = async () => { // retrieve XML }; // get XML const xml = await getResponseXML; // get users const names = xml.getElementsByTagName("name"); for (var i = 0; i < names.length; i++) { var name = names[i].firstChild.nodeValue; var div = document.createElement("div"); var textNode = document.createTextNode(name); div.appendChild(textNode); document.getElementById("wrapper").appendChild(div); }
Lets breakdown what happens here:
- Find element by tag name
name
- Loop through each name XML element
- For each element, get the inner
nodeValue
 which will give back the text - Create a new DOM node usingÂ
createTextNode
- Append this node to the DOM
While XML isn’t particularly friendly to traverse through, it’s quite manageable using these steps.
Additionally, if you are looking to test this method out with sample XML data. You can try the following snippet in your debugger tool:
const getUsers = (xml) => { // get users const names = xml.getElementsByTagName("from"); for (var i = 0; i < names.length; i++) { var name = names[i].firstChild.nodeValue; var div = document.createElement("div"); var textNode = document.createTextNode(name); document.getElementById("wrapper").appendChild(div); } }; const getResponseXML = async () => { // get XML // retrieve XML const xml = await fetch("https://www.w3schools.com/xml/note.xml"); const parsedXML = await xml.text(); console.log(new window.DOMParser().parseFromString(parsedXML, "text/xml")); getUsers(new window.DOMParser().parseFromString(parsedXML, "text/xml")); }; getResponseXML();