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
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:

  1. Find element by tag name name
  2. Loop through each name XML element
  3. For each element, get the inner nodeValue which will give back the text
  4. Create a new DOM node using createTextNode
  5. 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();

Gareth Dunne

Senior JavaScript Engineer and creator of JSdiaries. Passionate about the latest in web technologies and how it can provide value for my clients.