DOM Interfaces

The document processing can be done two ways:

  • Through generic Node interface.
  • Specific interface defined for each nodeType.

Generic Node interface

The node of XML element has a minimum set of attributes and methods which can be used to manipulate tree structure. A generic Node interface can access other nodes through parent node, child node, siblings …etc relationship. It is root of all specific interfaces and is possible to access any object of the document.

Attributes defined in a Node interface are firstChild, lastChild, nextSibling, parentNode, and previousSibling.

Example attributes in Node interface

<book>

      <title>Lamp is Lit</title>

      <author>Ruskin Bond</author>

</book>

Where:

  • First child of book is title.
  • Parent Node of title is book.
  • Last Child is author.
  • Next Sibling of title is author.
  • Previous Sibling of author is title.

Methods defined in Node interface are given below. A complete example of loading XML document and manipulating nodes are given at the end of the definitions. These code snippets can be placed at appropriate place in the code to get desired output.

insertBefore()

The insertBefore() method inserts new child node before specified child.

Syntax for insertBefore() method

xmldoc = loadXMLDoc(“myData.xml”);

newele = xmldoc.createElement(“newbooks”);

x = xmldoc.documentElement;

node = xmldoc.getElementsByTagName(“newbooks”)[3];

x.insertBefore(newele, node);

removeChild()

The removeChild() method removes a specific node from a document.

Syntax for removeChild() method

xmldoc = loadXMLDoc(“myData.xml”);

rem = xmldoc.getElementsByTagName(“newbooks”)[0];

xmldoc.document.removeChild(rem);

removeAttribute()

The removeAttribute() method removes specified attribute from document.

Syntax for removeAttribute() method

xmldoc = loadXMLDoc(“myData.xml”);

rem = xmldoc.getElementsByTagName(“newbooks”);

rem[0].removeAttribute(“cost”);

replaceChild()

The replaceChild() method replaces a specific child node from the document.

Syntax for replaceChild() method

xmldoc = loadXMLDoc(“myData.xml”);

newNode = xmldoc.createElement(“book”);

newName = xmldoc.createElement(“title”);

newText = xmldoc.createtextNode(“Fountain Pen”);

newName.appendChild(newText);

newNode.appendChild(newName);

createElement()

 The createElement() method creates a new element node.

Syntax for createElement() method

xmldoc = loadXMLDoc(“myData.xml”);

newele = xmldoc.createElement(“newbooks”);

createAttribute()

The createAttribute() method creates a new attribute node.

Syntax for createAttribute() method

xmldoc = loadXMLDoc(“myData.xml”);

newatt = xmldoc.createAttribute(“edition”);

setAttribute()

The setAttribute() method sets attribute if it exists or creates new attribute if it does not exists.

Syntax for setAttribute() method

xmldoc = loadXMLDoc(“myData.xml”);

t = xmldoc.getElementsByTagName(“title”);

t[0].setAttribute(“cost”,”290”);

createTextNode()

The createTextNode() method creates a new text node.

Syntax for createTextNode() method

xmldoc = loadXMLDoc(“myData.xml”);

t = xmldoc.createElement(“title”);

thisText = xmldoc.createTextNode(“A day in front of Fire”);

t.appendChild(thisText);

x=xmlDoc.getElementByTagName(“book”)[2];

x.appendChild(t);

createCDATASection()

The createCDATASection() method creates a new CDATA section mode.

Syntax for createCDATASection() method

xmldoc = loadXMLDoc(“myData.xml”);

c = xmldoc.createCDATASection(“This book is sold > 7000 copies”);

x=xmlDoc.getElementByTagName(“book”)[2];

x.appendChild(c);

createComment()

The createComment() method creates a new comment node.

Syntax for createComment() method

xmldoc = loadXMLDoc(“myData.xml”);

c = xmldoc.createComment(“Best seller of this season”);

x=xmlDoc.getElementByTagName(“book”)[2];

x.appendChild(c);

Example with general node interface methods in XML

The XML file and Javascript file to load the XML.

myData.xml

<?xml version='1.0'?>

<root>

    <data>

        <text>

        <author>P C Tejaswi</author>

        <books>Karvaalo</books>

        <award>State Academy</award>

        </text>  

               <text>

        <author>Kuvempu</author>

        <books>Ramayana Darshanam</books>

        <award>Gnanapeeta</award>

        </text> 

    </data>

</root>

myData.html

<!DOCTYPE html>

<html>

   <body>

      <h3>DOM usage </h3>

      <p id="para">    </p>

      <script>

            function loadFile(name){

         if (window.XMLHttpRequest)

         {// code for IE7+, Firefox, Chrome, Opera, Safari

            xhttp = new XMLHttpRequest();

         }

         else

         {// code for IE6, IE5

            xhttp = new ActiveXObject("Microsoft.XMLHTTP");

         }

         xhttp.open("GET",name,false);

         xhttp.send();

         return xhttp.responseXML;

            }          

      xmldoc = loadFile("myData.xml");

      document.write(xmldoc.documentElement.nodeName + " ");

            document.write(xmldoc.getElementsByTagName("author")[0].childNodes[0].nodeValue + " ");

            document.write(xmldoc.getElementsByTagName("book")[0].childNodes[0].nodeValue + " ");

            document.write(xmldoc.getElementsByTagName("award")[0].childNodes[0].nodeValue + " ");

      </script>

   </body>

</html>

//output

DOM usage

root P C Tejaswi Karvaalo State Academy

Specific node interface

DOM level 1 has defined following specific interfaces to manipulate the XML document nodes:

Document

 The Document interface refers to entire document.

DocumentFragment

The DocumentFragment interface represents fragment of XML document.

DocumentType

The DocumentType interface defines the DOCTYPE object.

EntityReference

The EntityReference interface represents the entity references of XML document.

Element

The Element interface refers to the element object of the XML document.

Attr

The Attr interface refers to the attribute of the Element object.

ProcessingInstruction

The ProcessingInstruction interface refers to the processing instructions in the document.

Comment

The Comment interface object represents content of comment in the document.

CDATASection

The CDATASection interface refers to CDATA section of the document.

Entity

The Entity interface represents parsed and unparsed data of XML.

Notation

The Notation interface is the non XML data in the XML document.

Node

The Node interface object represents single node in the document.

NodeList

The NodeList interface represents ordered list of nodes. The nodes can be accessed through index number starting from 0.  The node automatically updates the element added, deleted from the list.

This interface has length method which returns the length of the node list.

This interface has item() method which returns the node at the specified index of the node list.

Syntax for NodeList interface

Xmldoc = loadxml(“myData.xml”);

X = xmldoc.getElementsByTagname(‘author’)

document.write(x.item(0).nodeName);

NamedNodeMap

The NamedNodeMap interface represents unordered list of nodes. The nodes can be returned in any particular order and can be accessed by any name.

length method

The length method has a length attribute which returns the number of nodes.

Example of length method

      xmldoc = loadXMLDoc(“myData.xml”);

   x = xmldoc.getElementsByTagName(“book”);

   document.write(x.item(0).attributes.length);

getNamedItem()

The getNamedItem() method returns the node with given name.

Syntax for getNamedItem() method

namedNodeMap.getNamedItem(nodeName)

getNamedItemNS()

The getNamedItemNS() method returns a node with given name and namespace.

item()

The item() method returns node at given index.

Syntax for item() method

Node.item(index)

removeNamedIndex()

The removeNamedIndex() method removes the node with the given name.

Syntax for removeNamedIndex() method

namedNodeMap.removeNamedIndex(nodename)

removeNamedItemNS()

The removeNamedItemNS() method removes the node with given name and namespace.

setNamedItem()

The setNamedItem() method sets the name of given node.

setNamedItemNS()

The setNamedItemNS() method sets the name and namespace of the given node.

DOM Implementation

The DOM implementation has the list of methods which perform operations that are independent of any instance of DOM.The methods of DOM implementation are:

createDocument()

The createDocument() method returns a DOM Document object with specified type and doctype.

Syntax for createDocument() method

createDocument(namespaceURI, qualifiedName, doctype)

Where,

  • namespaceURI – Namespace URI fo the document to be created.
  • qualifiedName – Qualified name of the document to be created.
  • doctype – Type of document to be created.

createDocumentType()

The createDocumentType() method creates an empty DocumentType node and returns it.

Syntax createDocumentType() method

createDocumentType(name, pubId, systemId)

Where,

  • name is qualified name of the document type.
  • pubId is external subset public identifier.
  • systemId is external subset system identifier.

getFeature()

The getFeature() method returns an object which implements API’s of a specified feature and version.

Syntax getFeature() method

getFeature(feature, version)

Where,

  • feature is name of the feature to test.
  • version is the version number of the feature to test.

hasFeature()

  The hasFeature() method tests if the DOM implementation has implemented a particular feature.

Syntax hasFeature() method

getFeature(feature,version)

Where,

  • feature is name of the feature to test.
  • version is the version number of the feature to test.

DOM Exception

DOM operations raise exceptions when an operation is impossible to perform because of logical reasons, data is lost, etc... The DOM methods return the error values when exception occurs.

List of DOM Exception ID’s, values and description is given below:

List of DOM Exception ID’s, values and description

Error Name

Error Code ID

Description

DOMException.INDEX_SIZE_ERR

1

This error occurs if index is negative or greater than allowed value.

DOMException.DOMSTRING_SIZE_ERR

2

This error occurs if the range of text does not fit into the string.

DOMException.HIERARCHY_REQUEST_ERR

3

This error occurs if any Node is inserted somewhere it does n ot belong.

DOMException.WRONG_DOCUMENT_ERR

4

This error occurs if the node is used in another document than it was created.

DOMException.INVALID_CHARACTER_ERR

5

This error occurs if an invalid or illegal character is specified.

DOMException.NO_DATA_ALLOWED_ERR

6

This error occurs if the data specified for node is not allowed.

DOMException.NO_MODIFICATION_ALLOWED_ERR

7

This error occurs if the modification is attempted on an object where it is not allowed.

DOMException.NOT_FOUND_ERR

8

This error occurs if the node which does not exists is referenced

DOMException.NOT_SUPPORTED_ERR

9

This error occurs if the implementation does not support the requested type of object or operation.

DOMException.INUSE_ATTRIBUTE_ERR

10

This error occurs if the existing attribute is added to the document again.

DOMException.INVALID_STATE_ERR

11

This error occurs if the object that is no longer usable is attempted to use

DOMException.SYNTAX_ERR

12

This error occurs if an invalid or illegal string is specified.

DOMException.INVALID_MODIFICATION_ERR

13

This error occurs if the type of object is changed

DOMException.NAMESPACE_ERR

14

This error occurs if the objects are changed in a wrong way wrt namespaces.

DOMException.INVALID_ACCESS_ERR

15

This error occurs if the operation is not supported by the object.

DOMException.VALIDATION_ERR

16

This error occurs if validation error occurs after method such as insertBefore or removeChild is used.

DOMException.MISMATCH_ERR

17

This error occurs if type of element is incompatible with it’s expected type of the parameter associated.

 

›› go to examples ››