Exploring the XML Document Object Model

Discussion in 'JavaScript and AJAX' started by MinalS, Sep 16, 2014.

  1. MinalS

    MinalS New Member

    Joined:
    Jul 8, 2014
    Messages:
    138
    Likes Received:
    32
    Trophy Points:
    0
    The DOM enabled parser is used for accessing the features of the application. The parser reads the XML document and parses to check that it is valid. The in memory representation of the XML document containing the elements is organized in the tree structure. There are nodes in the structure.

    Implementation of DOM in the XML Parser



    The DOM implementation provides fundamental and programming interfaces. The DOMDocument and XMLDOMNode allows user to load or create the document. When the MSXML parser loads the XML document, it reads the document and creates the tree structure. The structure represents the components of the document.

    The structure of DOM tree for accessing the information stored in the XML documents is as shown below:

    [​IMG]

    DOM defines the logical structure of the XML document. The node is the basic building block of the tree structure. The nodes contain elements, attributes, content, and processing instructions.

    Consider the example of the STUDENT code snippet.

    Code:
    <STUDENTINFO>
    <STUDENT>
    	<STUDENTNAME>Mayank </STUDENTNAME>
    	<CLASS>BCA</CLASS>
    	<LOCATION>
    		<CITY>Mumbai</CITY>
    	</LOCATION>
    </STUDENT>
    </STUDENTINFO>
    
    The following diagram represents the XML DOM for the code snippet.

    [​IMG]

    The STUDENTINFO element represents the root node of the DOM tree structure. The STUDENT node acts as the child element of the root node. The other nodes are present in the STUDENT contains all the information as Class, Studentname and Location. The value of the node is the content that is stored in that node.

    Objects and Methods of the XML DOM



    The objects and the methods provided by the XML DOM are used to read, traverse and manipulate the structure and content of the XML document.

    1. The Document Object

    The document object is the top level object in the XML DOM structure. The methods that are required for creating the XML document are added in it. There are several methods and properties that can be used for modifying the content.

    Some of the properties and methods of the Document object are as mentioned below:
    • createElement ( element name ): It takes the element name as the input parameter and creates the element node with the corresponding name.

      The example of the method is as shown below:

      Code:
      docobj.createElement (“ STUDENT” );
      
    • createAttribute ( attribute name ): It takes the attribute name as the input parameter and creates the attribute node with that name.

      The syntax for creating the attribute node is as shown below:

      Code:
      docobj.createAttribute (“ StudID” );
      
    • createComment ( text ): It takes the string as the parameter and creates the comment node containing this string.

      The example for creating the comment is as shown below:
      Code:
      docobj.createComment (“ It is an XML document” );
      
    • createTextNode ( text ): It takes the string as the parameter and creates a text node.
      The example for creating the text node is as shown below:

      Code:
      docobj.createTextNode (“ Welcome User” );
      
    • createNode ( type, name, namespace – URI ): The type parameter can be integer or string. The name is the string parameter that states the name of the node to be created. The third parameter represents the namespace – URI.

      The example for creating the create node is as shown below:

      Code:
      docobj.createNode (“ element”, “STUDENT”, “www.google.com/Studentinfo” );
      
    • async: The property is used to specify that the asynchronous download is allowed or not. It takes a Boolean value. The example of async property is as shown below:

      Code:
      docobj.async = false;
      
    • childNodes: It returns the list of child nodes that belong to the parent node. The example for the childNodes property is as shown below:

      Code:
      var root =  docobj.childNodes.item (1)
      
    • documentElement: The property contains the root element of the XML document represented in the document.

      Code:
      var root = docobj.documentElement
      
    • firstchild: The property returns the first child node of the parent element. It is a read only property.

      Code:
      var firstelement = docobj.firstchild
      
    • lastchild: The property returns the last child of the parent node.

      Code:
      var lastelement= docobj.lastchild
      
    2. The Element Object

    The Element object represents all the element nodes in a document. The attributes are associated with the elements are the properties of the element.

    Some of the methods of the Element object are as shown below:
    • getAttribute ( attributeName ) : It returns the string value of the specified attribute. The example of the property is a shown below:

      Code:
      var obj = Student.getAttribute (“ StudID” );
      
    • normalize() : It puts the text nodes for the specified element and the child nodes into one text node. It does not return any value. The example is as shown below:

      Code:
      Element.normalize();
      
    • removeAttribute ( attributeName) : It removes the specified attribute’s value. The example is as shown below:

      Code:
      obj1.removeAttribute (“ country “);
      
    • setAttribute ( attributeName, attributeValue) : It inserts a new attribute. The example is as shown below:

      Code:
      obj1.setAttribute (“ Attri1”, “ New” );
      
    • getAttributeNS ( namespaceURI, qualifiedNamevalue): It returns the specified attribute based on the specified namespace and local name.

      Code:
      obj1.getAttributeNS ( “ www.google.com/Student” , “Attri1” );
      
    • removeAttributeNS ( namespaceURI, localName): It removes an attribute based on the specified namespace and the local name.

      Code:
      obj1.removeAttributeNS ( “ www.google.com/Student”, “Attri1” );
      
    3. The Node Object

    The Node object represents a single node in the XML document tree structure. It could be an element that contains the child elements.

    The properties of the Node object are as mentioned below:
    • nodeName: It returns the name of the node. The example is as shown below:

      Code:
      element1.text=”User Name”;
      
    • nodeType: It returns the type of the node. The example is as shown below:

      Code:
      document.write(n.nodeType);
      
    • childNodes: It returns the list of child nodes of the node represented by the Node object. The example is as shown below:

      Code:
      obj1 = objXMLDoc.documentElement,childNodes;
      
    • text: It returns the text value present in the Node object. The example is as shown below:

      Code:
      alert ( element1.text );
      
    • xml: It returns the XML code for the Node object. The example is as shown below:

      Code:
      document.write( “student.xml” );
      
    The methods of the Node object are as shown below:
    • appendChild ( newChild ): It appends the node newChild at the end of the child nodes for which it is used. The example is as follows:

      Code:
      nodeobj1.appendChild ( newElement );
      
    • insertBefore (newNode, refNode): It inserts the new node before the existing refNode. The example is as follows:

      Code:
      nodeobj1.insertBefore ( new_node, childNodes1.item (4) );
      
    • replaceChild ( newNode, oldNode ): The method replaces the oldNode with the newNode. The example is as shown below:

      Code:
      root.replaceChild ( new_node, root.childNodes.item (2));
      
    • hasChildNodes ( ) : It returns true if the object has child nodes. The example is as shown below:

      Code:
      If n.haschildNodes
      Then 
      Set n = n.firstchild
      
    4. The NodeList Object

    The NodeList object provides the list of nodes present in an XML document for manipulating data. It helps user to iterate through the collection of nodes.

    Some of the methods of the NodeList object are as listed below:
    • item ( number ): It returns the node at the position indicated by the specified number. The example is as shown below:

      Code:
      var obj1 = NodeList.item (3). firstChild.nodeValue;
      
    • nextNode(): The method returns the next node in the list. The example is as shown below:

      Code:
      Node1 = NodeList.nextNode
      
    5. The Attr Object

    The Attr object represents an attribute of an Element object. The Attr object is also the Node and inherits the properties and methods of the Node object. It cannot contain null value.

    The child nodes are used to represent the value of an attribute The child node contains text and EntityReferences nodes.

    6. The Text Object

    The object is used to represent the text inside the element of the tree.

    Some of the properties of the Text object are as mentioned below:
    • data: It sets or returns the text of the element. The example for is as shown below:

      Code:
      x.xmlDoc.getElementByName (“Course”) [0]. childNodes [0];
      document.write (x.data);
      
    • length: It returns the length of the text element or attribute.

      Code:
      x.xmlDoc.getElementByName (“Course”) [0]. childNodes [0];
      document.write (x.length);
      
    • wholeText: It returns all the text nodes adjacent to the node and are concatenated in the order.
    Some of the methods of the Text Object are as listed below:
    • appendData(): It appends the data to the node. The example is as shown below:

      Code:
      x.xmlDoc.getElementByName (“Course”) [0]. childNodes [0];
      x.appendData(“Medicine”);
      document.write (x.data);
      
    • deleteData(): It deletes the data from the node. The example is as follows:

      Code:
      x.xmlDoc.getElementByName (“Course”) [0]. childNodes [0];
      x.deleteData(0.3);
      document.write (x.data);
      
    • insertData(): It inserts the data into the node. The example is as follows:

      Code:
      x.xmlDoc.getElementByName (“Course”) [0]. childNodes [0];
      x.insertData(0, “MBA”);
      document.write (x.data);
      
    • replaceData(): It replaces the data in the node. The example is as shown below:

      Code:
      x.xmlDoc.getElementByName (“Course”) [0]. childNodes [0];
      x.replaceData(0,4, “Welcome” );
      document.write (x.data);
      
    • splitText(): It splits the text at the specified character and returns the text.
      The example is as shown below:

      Code:
      x.xmlDoc.getElementByName (“Course”) [0]. childNodes [0];
      y=x.splitText(4);
      document.write (x.data);
      
    7. The CDataSection Object

    The CDataSection object represents a CDATA section in a document. It contains text that is not processed by the parser. The tags inside are not considered as markup or entities.

    8. The ParseError Object

    The ParseError Object contains the information about the latest parse error. It provides properties to collect information as error text, error code.

    Some of the properties of the ParseError object are as mentioned below:
    1. errorCode: It returns the long integer error code.
    2. reason: It returns the string containing the reason for the error.
    3. line: It returns the long integer representing the line number of the error.
    4. linePos: It returns the long integer representing the line position for the error.
    5. srcText: It returns the string containing the line that caused the error.
    Consider the following example demonstrating the ParseError object.

    Code:
    var xmlDoc = new ActiveObject (“ Microsoft.XMLDOM1” );
    xmlDoc.async=false;
    xmlDoc.load(“OrderDetails.xml”);
    document.write( “ Error code: “+xmlDoc.parseError.errorCode );
    document.write( “ Error Reason: “+xmlDoc.parseError.reason );
    
    The example demonstrating the DOM object is as shown below:

    Create an xml file as EmpDetails. The code in the file is as shown below:

    Code:
    <? xml version =”1.0” encoding=”utf-8” ?>
    <EmpDetails>
    	<Emp>
    	<EmpName>John</EmpName>
    	<EmpRole>Manager</EmpRole>
    	<Location>Pune</Location>
    	</Emp>
    	<Emp>
    	<EmpName>Mark</EmpName>
    	<EmpRole>Lead</EmpRole>
    	<Location>Mumbai</Location>
    	</Emp>
    </EmpDetails>
    
    The .htm file consists of the following code.

    Code:
    <html>
    <head>
    	<script language=”javascript” >
    	function Navigate ()
    	{
    		var xmldoc = new ActiveXObject(“ Microsoft.XMLDOM”);
    		var i;
    		xmldoc.async = false;
    		xmldoc.load (“XMLFile.xml “);
    		if ( xmldoc.readystate == 4 && xmldoc.parseError.errorCode == 0)
    		{
    			var root = xmldoc.documentElement;
    			for ( i=0; i<root.childNodes.length; i++)
    			{
    				alert (root.childNodes.item(i).xml);
    			}
    		}
    		else
    		{
    			alert ( “Document loading is not possible” );
    		}
    	}
    	</script>
    </head>
    <body onload=”javascript:Navigate()”>
    </body>
    </html>
    
    The output for the code is as shown below:

    [​IMG]
     
    Last edited by a moderator: Jan 21, 2017

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice