The example adds attribute name and value to the <data> element of the xml document. It also displays the name and textContent attributes.

myData.xml

<?xml version='1.0'?>

<root>

    <data>

        <animal>Lion</animal>

            <habitat>jungle</habitat>

            <type>mammal</type>

            <eatingHabit>Carnivore</eatingHabit>

    </data>

     

      <data>

        <animal>Deer</animal>

            <habitat>jungle</habitat>

            <type>mammal</type>

            <eatingHabit>Herbivore</eatingHabit>

    </data>

</root>

myData.html

<!DOCTYPE html>

<html>

   <body>

      <h1>Adding Attribute </h1>     

      <script>

            function loadFile(name){

                   if (window.XMLHttpRequest)

                   {// code for IE7+, Firefox, Chrome, Opera, Safari

                        xmlhttp = new XMLHttpRequest();

                   }

                   else

                   {// code for IE6, IE5

                        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

                   }

                  xmlhttp.open("GET",name,false);

                  xmlhttp.send();

                  return xmlhttp.responseXML;

 

            }

           

            xmlDoc = loadFile("myData.xml");         

            x=xmlDoc.getElementsByTagName("data");

           

            for(i=0; i<x.length; i++){

                  newAttr=xmlDoc.createAttribute("censusYear");

                  newAttr.nodeValue="2015";    

                  x[i].setAttributeNode(newAttr);    

            }

                       

            for (i=0; i<x.length; i++)

              {

                  document.write("censusYear for node" + i + " has attribute value " + x[i].getAttribute("censusYear") + "<br/>");              

                  document.write("name:" + x.item(i).attributes[0].name + " textContent: " + x.item(i).attributes[0].textContent + "<br/>");

              }          

           

      </script>

   </body>

</html>

Output from example:

Adding Attribute

censusYear for node0 has attribute value 2015
name:censusYear textContent: 2015
censusYear for node1 has attribute value 2015
name:censusYear textContent: 2015