Parsing XML Document using Javascript

This section contains a lot of Scripting material for your website.

Parsing XML Document using Javascript

Postby php developer on July 30th, 2008, 6:07 am

To manipulate an XML document in javascript, you need an XML parser. Today all browsers come with in-built parsers that can parse the XML document. The parser loads the document into your computer’s memory. Once the document is loaded, its data can be manipulated using the DOM(Document Object Model). There is significant differences in implementation of Microsoft Browser based XML parser and the Mozilla browsers based XML parser.

XML Parser in Microsoft Browser:
Microsoft’s XML parser is a COM component that comes with Internet Explorer 5 and higher. To load the XML Parser in JavaScript will have to follow series of steps.

1. Create instance of XML Parser:
Code: Select all
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");

This will load the xml parser in the memory and will wait for the xml document. This component will automatically get erased when you close the browser window or the Browser. Here the xmlDoc holds the XML Object for JavaScript.

2. Synchronous load the XML Data
Code: Select all
xmlDoc.async="false";

This line turns off asynchronous loading, to make sure that the parser will not continue execution of the script before the document is fully loaded.

3. Callback function
Code: Select all
xmlDoc.onreadystatechange = function name

Calls the callback function on change of every state while loading the xml document.

ReadyStates in Microsoft Browsers
1. Loading: Preparing to read the XML file. Did not try yet
2. Loaded Parsing the XML file: Object model still not available
3. Interactive: Part of XML file successfully parsed and read in. Object model partially available for read only
4. Completed: Loading of the XML file has been completed, successfully or unsuccessfully

4. Load XML Document
Code: Select all
xmlDoc.load("note.xml");

Tells the parser to load note.xml file.

XML Parser in Firefox/Opera Browsers:
Similar to Microsoft IE, Mozilla Firefox and Opera browsers too comes with their own xml parsers. To load the XML Parser in JavaScript will have to follow series of steps:

1. Create instance of XML Parser
Code: Select all
var xmlDoc=document.implementation.createDocument("","",null);

This will load the xml parser in the memory and will wait for the xml document. This component will automatically get erased when you close the browser window or the Browser. Here the xmlDoc holds the XML Object for JavaScript.

2. Load XML Document
Code: Select all
xmlDoc.load("note.xml");

This line tells the parser to load an XML document called “note.xml”.

3. Callback function
Code: Select all
xmlDoc.onload=function-name

This line tells the parser to call function when the XML document is loaded.

Properties of XML Parsers in JavaScript:
The XML Object comes with inbuilt properties that allows easy iterate to the XML document. To easily understand these properties i am going to refer to the below XML file and the code for loading the XML file is also written below.

employee.xml
Code: Select all
< ?xml version="1.0" encoding="UTF-8" ?>
   <company>
      <employee id="001" >John</employee>
      <turnover>
         <year id="2000">100,000</year>
         <year id="2001">140,000</year>   
         <year id="2002">200,000</year>
      </turnover>
   </company>


Snippet for loading employee.xml(Microsoft Browsers)
Code: Select all
<html>
<head>
  <title>Read XML in Microsoft Browsers</title>
  <script type="text/javascript">
    var xmlDoc;
    function loadxml()
    {
      xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async = false;
      xmlDoc.onreadystatechange = readXML;
      xmlDoc.load("employee.xml");
    }

    function readXML()
    {
       if(xmlDoc.readyState == 4)
       {
        //Using documentElement Properties
        //Output company
        alert("XML Root Tag Name: " + xmlDoc.documentElement.tagName);

        //Using firstChild Properties
        //Output year
        alert("First Child: " + xmlDoc.documentElement.childNodes[1].firstChild.tagName);

   //Using lastChild Properties
   //Output average
   alert("Last Child: " + xmlDoc.documentElement.childNodes[1].lastChild.tagName);

   //Using nodeValue and Attributes Properties
   //Here both the statement will return you the same result
   //Output 001
   alert("Node Value: " + xmlDoc.documentElement.childNodes[0].attributes[0].nodeValue);
   alert("Node Value: " + xmlDoc.documentElement.childNodes[0].attributes.getNamedItem("id").nodeValue);

   //Using getElementByTagName Properties
   //Here both the statement will return you the same result
   //Output 2000
   alert("getElementsByTagName: " + xmlDoc.getElementsByTagName("year")[0].attributes.getNamedItem("id").nodeValue);

   //Using text Properties
   //Output John
   alert("Text Content for Employee Tag: " + xmlDoc.documentElement.childNodes[0].text);

   //Using hasChildNodes Properties
   //Output True
   alert("Checking Child Nodes: " + xmlDoc.documentElement.childNodes[0].hasChildNodes);
      }

  </script>
</head>

<body onload="loadxml();">

</body>
</html>


Note: XML Object properties are case-sensitive.

The various properties of XML Parsers are:

documentElement
documentElement property will always point to the root element of the xml document.
Syntax: xml_object.documentElement

Referring to the above code Line 20 will point to company tag and tagName will return company.

childNodes
childNodes property will always hold array of children nodes from the current pointing node.
Syntax: xml_object.current_pointing_node.childNodes[Array Index]

firstChild
This property will point to the first occurance of the child node found from the current pointing node. IE Specific
Syntax: xml_object.firstChild

Referring to the above code Line 24 will point to year tag and tagName will return year.

lastChild
Will point to the last occurance of the child node found from the current pointing node. IE Specific
Syntax: xml_object.lastChild

Referring to the above code Line 28 will point to average tag and tagName will return average.

attributes
Allows you to access the attributes values for the elements. This proerty is used along with the nodeValue property.
Syntax: xml_object.current_pointing_node.attributes[Attribute Name/Array Index]

Referring to the above code Line 33 and 34 will point to employee tag and will return the value assigned to id Attribute.

nodeValue
Return you the values assigned to the attributes. This properties is only used to extract the attribute content.
Syntax: xmlDoc.current_pointing_node.attributes[Attribute Name/Array Index].nodeValue

Referring to the above code Line 33 and 34 will point to employee tag and will return the value assigned to id Attribute.

getElementsByTagName
This properties allows you to point to any tag name provided you have to specify that tag name as a parameter. So it is mandatory to know the xml structure to use this property. It always returns an array of nodes.
Syntax: xml_object.getElementsByTag(Tag Name)

Referring to the above code Line 39 will point to year tag and will return the value assign to id attribute for the first year tag only.

text
Returns the text content assigned to the tag elements. This property cannot be used for reading attribute content. Also this property can only be used for Microsoft Browsers
Syntax: xml_object.current_pointing_node.text

Referring to the above code Line 43 will point to employee tag and will return John.

textContent
Returns the text content assigned to the tag elements. This property cannot be used for reading attribute content. Also this property can only be used for Mozilla, Firefox, Opera Browsers
Syntax: xml_object.current_pointing_node.textContent

hasChildNodes
Return boolean value indicating the current pointing node has child nodes or not.
Syntax: xml_object.hasChildNodes

Referring to the above code Line 47 will return True as the company tag has childnodes.

tagName
Return you the element name
Syntax: xml_object.current_pointing_node.tagName

Referring to the above code Line 20 it points to company tag and return the company.
php developer
 
Posts: 25
Joined: July 25th, 2008, 4:56 am

Return to Java Script / VB Script

Who is online

Users browsing this forum: No registered users and 0 guests

cron