Sunday, March 25, 2012

Navigating XML DOM with javascript Complete Code

The full code for the XML DOM navigation can be copied and tested in your browser


<html>
    <head>
        <title>
        </title>
        <style type="text/css">
            body {
                margin: 0px;
            }
        </style>
        <script type="text/javascript">


        // put the document into a javascript string variable
        var xmltxt = "<customerlist>";
        xmltxt +=    "<customer>";
        xmltxt +=    "<name>John Doe</name>";
        xmltxt +=    "<address>1 Main Street</address>";
        xmltxt +=    "<tel>123-456-7890</tel>";
        xmltxt +=    "</customer>";
        xmltxt +=    "<customer>";
        xmltxt +=    "<name>Jane Doe</name>";
        xmltxt +=    "<address>3 Main Street</address>";
        xmltxt +=    "<tel>987-654-3210</tel>";
        xmltxt +=    "</customer>";
        xmltxt +=    "</customerlist>";

        // load the xml string variable into a DOM object. The code syntax for firefox &
        // other browsers differ from i.e. so you have to code for the users browser

        if(window.DOMParser){
                // non i.e. browser
            xmlparser = new DOMParser();
            xmlDoc = xmlparser.parseFromString(xmltxt, "text/xml");
        }else{
            // i.e. browser
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = false;
            xmlDoc.loadXML(xmltxt);
        }


            root = xmlDoc.getElementsByTagName("customerlist")[0];
            customers = root.childNodes;

            customer1namenode = customers[0].firstChild;
            customer1telnode = customers[0].lastChild;

            alert(customer1namenode.nodeName);/
            alert(customer1namenode.childNodes[0].nodeValue);

            addressnode = customer1namenode.nextSibling;
            alert(addressnode.firstChild.nodeValue);

        </script>
    </head>
    <body>
        You should see DOM alerts
    </body>
</html>



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

Javascript Arrays

Javascript setTimeout

YouTube Player API

Javascript DOM Functions

XML (Extensible Markup Language)

Create your first facebook application

Get rid of space at top of my web page

To get rid of the space at the top of the web page you should specify 0 margin for the body tag. This can be done two ways.

<html>
    <head>
        <title>
            Annoying space at top of web page
        </title>
    </head>
    <!-- you can create a style tag in the header -->
    <style type="text/css">
        body {
            margin: 0px;
        }
    </style>
    <body style="margin: 0px;"> <!-- or you can put as a style in the body tag -->
    </body>
</html>

Javascript alert() Function

Javascript For Loop

Node.parentNode

Node.childNodes

Node.previousSibling Javascript

Node.nextSibling Javascript

Node.lastChild Javascript

Javascript XML DOM Manipulation

Navigating the DOM with javascript is very useful. You can access any  data in the xml document that you wish. Manipulating that data is also another powerful feature available in javscript. You can update node values, remove, delete and create nodes on the fly.

Changing A Node Value

Node.firstChild Javascript

Returns the first node in the child collection for the Node

getElementsByTagName Javascript

XMLDocument.getElementsByTagName(nodename);
node.getElementsByTagName(nodename);

Returns an array of nodes with "nodename" as the element name.

Navigating XML DOM with javascript Contd.

childNodes


Now that you have the root element you can take advantage of the other properties for DOM navigation.
The Node.childNodes property returns an array of nodes that are children of the node it is being called upon.
Lets look at the 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>

The following code will get an array containing the two customer nodes, which are children of the root <customerlist> node:

root = xmlDoc.getElementsByTagName("customerlist")[0];
customers = root.childNodes;


The first element in the arraycustomers[0] will be the node with John Doe, customers[1] will be the node with Jane Doe.

firstChild, lastChild


Now we have a customer node we can test two other DOM properties on it. The node.firstChild and node.lastChild properties return the first and last child nodes of the node it is referencing. Using the customers array we can get the "name" and "tel" node for John Doe.


root = xmlDoc.getElementsByTagName("customerlist")[0];
customers = root.childNodes;
customer1namenode = customers[0].firstChild;
customer1telnode = customers[0].lastChild; 


Now you have accessed data containing nodes and can read the data in them. This is done using the node.nodeValue property. However, the data within the node cannot be accessed directly as the DOM wraps all text data into a text node:

alert(customer1namenode.nodeValue); // is not incorrect


alert(customer1namenode.firstChild.nodeValue); 


previousSibling, nextSibling


Up to this point we have not managed to access the address node for the customer. We could use getElementsByTagName but as mentioned before its not heirarchy safe and we would get an array of <address> nodes with no knowledge of which belonging to what. The node.previousSibling and node.nextSibling properties give a way to step through the child nodes given we have one of the parentnode. We could get the address node by 


addressnode = customer1namenode.nextSibling;
or
addressnode =  customer1telnode .previousSibling; 


Similarly we could have access the address from the childnodes array

customers[0].childNodes[1];
/*
where childnodes[0] is the name 
      childnodes[1] is the address 

      childnodes[2] is the tel
*/



parentNode


The node.parentNode property returns the node that is above the current node it is called upon in the heirarchy.


root = xmlDoc.getElementsByTagName("customerlist")[0];
customers = root.childNodes;
alert(customers[0].parentNode.nodeName);



The above will show "customerlist" in the alert dialog since it is the element directly above the <customer> element in the heirarchy.


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

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

Javascript XML processing

XML (extensible markup language) is a widely used data format for storing and transferring information, which is both computer processable and human readable. Javascript provides a powerful tool to manipulate xml documents in its DOM processing library. In this tutorial we'll build  basic javascript xml parser.

Lets begin by using a basic XML example. Our sample XML document will be a table of customers with two entries

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

We load the document into an XML DOM object with the following javascript code:

// put the document into a javascript string variable

var xmltxt = "<customerlist>";

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


// load the xml string variable into a DOM object. The code syntax for firefox & 
// other browsers differ from i.e. so you have to code for the users browser

if(window.DOMParser){
    // non i.e. browser
    xmlparser = new DOMParser();
    xmlDoc = xmlparser.parseFromString(xmltxt, "text/xml");
}else{
    // i.e. browser
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(xmltxt);
}

Now the DOM object is loaded with the xml document containing the table of customers, you can use the DOM object to do intersting things as will be seen in the next section.

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



Related Link
Extensible Markup Language - Wikipedia