Sunday, March 25, 2012

Navigating XML DOM with javascript


After you have loaded the XML DOM object you can begin processing and navigating the document with the many properties available in the DOM object. Lets look at the customer xml document again:

<customerlist>
     <customer>
         <name>John Doe</name>
         <address>1 Main Street</address>
         <tel>123-456-7890</tel>
     </customer>
     <customer>
         <name>Jane Doe</name>
         <address>3 Main Street</address>
         <tel>987-654-3210</tel>
     </customer>
</customerlist>

All xml documents are organized in a tree structure so naturally there would be a root element in the DOM. In this case the root element is the <customerlist> node. It has two child <customer> nodes and each <customer> node has a <name>,  <address> and <tel> node. A graphical illustration of the document heirarchy is provided below:

                                                                                customerlist
                                                ____________________|____________
                                                |                                                                |
                                         customer                                                    customer
                            __________|___________                        __________|__________
                            |                   |                      |                       |                    |                   |
                       name          address                 tel                  name          address             tel


The node accessing properties available in javascript are:

getElementsByTagName
childNodes
firstChild
lastChild
nextSibling
previousSibling
More DOM properties and functions 


getElementsByTagName


You can get a hold of the root node by using the getElementsByTagName function as in the following code:

root = xmlDoc.getELementsByTagName("customerlist")[0];

the DOMDocument.getElementsByTagName("nondename") function returns an array of all nodes with the name "nodename". The bracketed 0 at the end is to get the first array element which we assign to the root variable.
Similarly, the code could be written as:

customerlistarray = xmlDoc.getELementsByTagName("customerlist");
root = customerlistarray[0];


The getElementsByTagName function is however not heirarchy specific. If you passed "name" as an argument it would return an array of the two "name" nodes, so it can  be used to randomly access nodes in the DOM. This is why I used it to grab the root node. 

Alternatively the root node can be accessed by using the Node.firstChild Property on the DOM Document object

root = xmlDoc.firstChild;

 Next - Navigating XML DOM with javascript Contd

Javascript XML processing
Navigating XML DOM with Javascript
Navigating XML DOM with javascript Contd.
Navigating XML DOM with javascript Code

1 comment: