Push XML Attributes into an Array using JavaScript

← PrevNext →

Let us assume, I have an XML file and I want to extract data from it using JavaScript. Before I do anything with the extracted data, I want to store data from each attribute in an array. So, how do I push the XML attributes into an array using JavaScript? Its simple.

Let us first understand elements and attributes. XML elements are like HTML elements. Elements have attributes and each attribute contain data. For example,

<Bird name="Bald Eagle" id="001">
    <type>Hawk</type>
</Bird>

There are two different elements in the above XML. The first is element <Bird> and second is element <type> (it's a nested element). In-addition, there are two attributes (name and id) inside the element <Bird>. I want to push the attributes (only) into an array.

The XML file

Here's the XML file. Each <Bird> element has two attributes and one nested element.

The Script
<script>
let get_xml = () => {
  const oXHR = new XMLHttpRequest(); // Create XMLHttpRequest object.

  // Initiate request.
  oXHR.onreadystatechange = reportStatus;
  function reportStatus() {
    if (oXHR.readyState == 4)
      read_data(this.responseXML);
  }
  oXHR.open('GET', 'list_of_birds.xml', true);
  oXHR.send();

  function read_data(xml) {
    let arr = [];

    ucList = xml.getElementsByTagName('Bird');  // Its Bird with "B" not bird.
    
    for (let i = 0; i < ucList.length; i++) 
    {
      // Push XML attributes into the array.
      arr.push({
        name: ucList[i].getAttribute('name'),
        id: ucList[i].getAttribute('id')
      });
    }
    
    // Show the data from the attributes.
    for (let j = 0; j < arr.length; j++)
    {
        document.write (arr[j].id + ' ' + arr[j].name + '   <br />');
    }
  }
}

get_xml();

</script>
Try it

See the .getAttribute() method in the above script. The method takes a parameter, the name of an XML attribute. It returns a value (data) assigned to the attribute. For example,

console.log (xml.getElementsByTagName('Bird')[0].getAttribute('name'));

The output is the name of the bird in the 0 index.

Push XML Elements and Attributes into an Array

In-addition, you can "push" the elements in the same array like this. See the XML file again. There’s an element named <type>. Here’s how you can add the element into the array.

arr.push({
    name: ucList[i].getAttribute('name'),
    id: ucList[i].getAttribute('id'),
    type: ucList[i].getElementsByTagName('type')[0].childNodes[0].nodeValue
});
Try it

Here's another example explaining how to push xml into an an array and convert data to an HTML table.

← PreviousNext →