XML - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

XML DOM

XML DOM

shape Introduction

In the present chapter, a much more powerful way of working with XML data called Document Object Model(DOM) will be discussed. DOM is very flexible and powerful and provides a much better way of working with XML data from a flexibility stand point than many other methods. The DOM was adopted by W3C as a standard in 1998 and there are several revisions since then. The DOM provides a standardized way of discovering, manipulating and changing the content of a document using common programming techniques that are probably used in languages like JavaScript or C++ or C#.

shape Description

DOM is platform browser and language neutral. It does not assume anything about what platform is running on what browser turning on and there are several language implementations of the DOM that can be used to work with. One of the most common languages that people work with the DOM is JavaScript. Using XML DOM the user can add, edit, remove, or move nodes in the tree at any point in order to create an application.

XML DOM Node

shape Description

The DOM represents DOM as a tree structure which is called as node-tree structure and allows access to the objects in the tree using a set of programming functions and properties. All the XML content such as elements, comments, processing instructions, CDATA sections are presented as objects. These objects are generically referred to as Nodes. Notice that they are not called as elements. An element is a type of node. Nodes in a document have parent-child relationship. Node Relationships: The terms parent, child, and sibling defines the relationships in DOM Tree. Parent nodes have children. Children on the same level are called Siblings (brothers or sisters). Every node, except the root, has exactly one parent node. A node can have any number of children and Siblings can be referred as nodes with same parent.

shape Example

Below is the basic example for XMl DOM in which bookstore is the node root which possess all the other nodes cooking, children, web. Each of the node has four nodes indeed like title, author, price, and year. [xml] <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="web"> <title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> <book category="web" cover="paperback"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore> [/xml]

Accessing Nodes

shape Description

A XML Node can be accessed in three ways. They are:

getElementsByTagName()

getElementsByTagName() returns all elements with a specified tag name. Syntax: [xml]node.getElementsByTagName("tagname");[/xml] Example: Below is the example for getElement ByTagName() method which uses x as the node and all the <p> elements under the x. [xml]x.getElementsByTagName("p");[/xml] If needed to return all the elements of the <p> XML Document, then use the below code. [xml]xmlDoc.getElementsByTagName("p");[/xml]

Looping the nodes tree

The below code consists of root node and child nodes. The process of looping will be undergone through child nodes. This process is also termed as Traversing. Example: [javascript] var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); function myFunction(xml) { var x, i, xmlDoc, txt; xmlDoc = xml.responseXML; txt = ""; x = xmlDoc.documentElement.childNodes; for (i = 0; i < x.length; i++) { if (x[i].nodeType == 1) { txt += x[i].nodeName + "<br>"; } } document.getElementById("demo").innerHTML = txt; } [/javascript] In the above example, books.xml is the XML document with the root element xmlDoc and to check the child nodes are present or not, loop is applies. If the nodeType equals to 1 then it is considered as element node and outputted as same.
As discussed Parent nodes have Children. Children of same level are called Siblings (brothers or sisters). Every node, except the root, has exactly one parent node. A node can have any number of children and Siblings can be referred as nodes with same parent. Example: [javascript] var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); function myFunction(xml) { var x, y, i, xlen, xmlDoc, txt; xmlDoc = xml.responseXML; x = xmlDoc.getElementsByTagName("book")[0]; xlen = x.childNodes.length; y = x.firstChild; txt = ""; for (i = 0; i < xlen; i++) { if (y.nodeType == 1) { txt += i + " " + y.nodeName + "<br>"; } y = y.nextSibling; } document.getElementById("demo").innerHTML = txt; } [/javascript]

Creating Nodes

shape Description

To create a element node in XML, use the method createElement(). Syntax: [xml]newElement = rootElement.createElement("elementName");[/xml] In the below example, the XML document is loaded into the root element xmlDoc. Then created the "edition" element node and add the same to the book element. [javascript] var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); function myFunction(xml) { var x, y, i, newElement, txt, xmlDoc; xmlDoc = xml.responseXML; newElement = xmlDoc.createElement("edition"); x = xmlDoc.getElementsByTagName("book")[0] x.appendChild(newElement); // Display all elements xlen = x.childNodes.length; y = x.firstChild; txt = ""; for (i = 0; i < xlen; i++) { if (y.nodeType == 1) { txt += y.nodeName + "<br>"; } y = y.nextSibling; } document.getElementById("demo").innerHTML = txt; } [/javascript]

Creating Attribute Nodes

To create a attribute node in XML, use the method createAttribute(). Syntax: [xml]newAtt = rootElement.createAttribute("attributeName");[/xml]

Creating Attribute using setAttribute()

To create a text node in XML, use the method setAttribute(). Syntax: [xml]xmlDoc.getElementsByTagName('book')[0].setAttribute("edition","first");[/xml] In the above syntax, xmlDoc is the root element, edition is the attribute node and first is the nodeValue.

Creating Text node

To create a attribute node if the attribute is not present in XML, use the method createAttribute(). Syntax: [xml]newText = xmlDoc.createTextNode("first");[/xml] Before creating the text node, element node has to be created.

Replacing Nodes

shape Description

To replace any node in XML DOM Tree, the method replaceChild() has to be used. This method will have 3 parameters:
  • offset - This parameter tells where to start the replacement of characters. By default, starts at 0.
  • length - length parameter number of characters to be replaced.
  • string - This parameter replaces the place with desired string.
Syntax: [xml]newText = xmlDoc.createTextNode("first");[/xml] Example: [javascript] var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); function myFunction(xml) { var x, y, z, i, newNode, newTitle, newText, xmlDoc, txt; xmlDoc = xml.responseXML; txt = ""; x = xmlDoc.documentElement; // Create a book element, title element and a text node newNode = xmlDoc.createElement("book"); newTitle = xmlDoc.createElement("title"); newText = xmlDoc.createTextNode("A Notebook"); // Add a text node to the title node newTitle.appendChild(newText); // Add the title node to the book node newNode.appendChild(newTitle); y = xmlDoc.getElementsByTagName("book")[0]; // Replace the first book node with the new book node x.replaceChild(newNode, y); z = xmlDoc.getElementsByTagName("title"); // Output all titles for (i = 0; i < z.length; i++) { txt += z[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("demo").innerHTML = txt; } [/javascript]

Summary

shape Key Points

  • Using XML DOM the user can create, edit, remove, or move nodes in the tree.
  • getElementsByTagName() returns all elements with a specified tag name.