XML - DOM

The Document Object Model (DOM) is the foundation of XML. XML documents have a hierarchy of informational units called nodes; DOM is a way of describing those nodes and the relationships between them.

A DOM document is a collection of nodes or pieces of information organized in a hierarchy. This hierarchy allows a developer to navigate through the tree looking for specific information. Because it is based on a hierarchy of information, the DOM is said to be tree based.

The XML DOM, on the other hand, also provides an API that allows a developer to add, edit, move, or remove nodes in the tree at any point in order to create an application.

Example

The following example (sample.htm) parses an XML document ("address.xml") into an XML DOM object and then extracts some information from it with JavaScript −

<!DOCTYPE html>

<html>

   <body>

      <h1>Softecks  DOM example </h1>

      <div>

         <b>Name:</b> <span id = "name"></span><br>

         <b>Company:</b> <span id = "company"></span><br>

         <b>Phone:</b> <span id = "phone"></span>

      </div>

      <script>

         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","/xml/address.xml",false);

         xmlhttp.send();

         xmlDoc = xmlhttp.responseXML;

 

         document.getElementById("name").innerHTML=

            xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;

         document.getElementById("company").innerHTML=

            xmlDoc.getElementsByTagName("company")[0].childNodes[0].nodeValue;

         document.getElementById("phone").innerHTML=

            xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue;

      </script>

   </body>

</html>

Contents of address.xml are as follows −

<?xml version = "1.0"?>

<contact-info>

   <name>Tanmay Patil</name>

   <company>Softecks </company>

   <phone>(011) 123-4567</phone>

</contact-info>

Now let us keep these two files sample.htm and address.xml in the same directory /xml and execute the sample.htm file by opening it in any browser. This should produce the following output.