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