Chapter-6 XML DOM

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 66

Chapter-6

X M L D O C U MEN T O B J E CT M O D EL ( D O M )

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
1
What is the DOM?
The DOM defines a standard for accessing and manipulating
documents:
A platform and language-neutral interface that allows
programs and scripts to dynamically access and update the
content, structure, and style of a document.

Two types of DOM


◦ HTML DOM
◦  Defines a standard way for accessing and manipulating HTML documents
◦ XML DOM
◦  defines a standard way for accessing and manipulating XML documents

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
2
XML DOM
A standard object model for XML

A standard programming interface for XML

Platform- and language-independent

A W3C standard

A standard for how to get, change, add, or delete XML


elements.

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
3
Get the Value of an XML Element

 This code retrieves the text value of the first <title> element in an XML
document:

 E.G.

txt= xmlDoc.getElementsByTagName(“title”)[0].childNodes[0].nodeValue;

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
4
The XMLHttpRequest Object
The XMLHttpRequest object is used to exchange data with a
server behind the scenes.

With XMLHttpRequest object we can:


◦ Update a web page without reloading the page

◦ Request data from a server after the page has loaded

◦ Receive data from a server after the page has loaded

◦ Send data to a server in the background

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
5
Create an XMLHttpRequest Object
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
 }
else
  {// code for IE6, IE5
  xmlhttp=new
ActiveXObject("Microsoft.XMLHTTP");
 }

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
6
Send a Request To a Server

We use the open() and send() methods of the

XMLHttpRequest object:

xmlhttp.open("GET","xmlhttp_info.txt",true);

xmlhttp.send();

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
7
Cont’d …

Method Description

open(method,url,async) Specifies the type of request, the URL, and if the request should be
handled asynchronously or not.

method: the type of request: GET or POST


url: the location of the file on the server
async: true (asynchronous) or false (synchronous)

send(string) Sends the request off to the server.

string: Only used for POST requests

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
8
GET or POST?
GET is simpler and faster than POST, and can be used in
most cases.

However, always use POST requests when:


◦ A cached file is not an option (update a file or database on the server)

◦ Sending a large amount of data to the server (POST has no size


limitations)
◦ Sending user input (which can contain unknown characters), POST is
more robust and secure than GET
DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
9
The URL - A File On a Server
The url parameter of the open() method, is an address to a
file on a server:
◦ xmlhttp.open("GET","xmlhttp_info.txt",true);

The file can be of any type.

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
10
Asynchronous - True or False?
Asynchronoustrue

SynchronousFalse
◦ Sending asynchronously requests is better,

◦ and its a \huge improvement for web developers.

By sending asynchronously, the JavaScript does not have to wait for the
server response, but can instead:
◦ execute other scripts while waiting for server response

◦ deal with the response when the response ready

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
11
Server Response
responseXML  receive response resource as XML

responseText receive response resource as plain text file

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
12
The onreadystatechange event
When a request to a server is sent, we want to perform some
actions based on the response.

The onreadystatechange event is triggered every time the


readyState changes.

The readyState property holds the status of the


XMLHttpRequest.

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
13
Cont’d …
Three important properties of the XMLHttpRequest object:

Property Description
onreadystatechang Stores a function (or the name of a function) to be called automatically each time
e the readyState property changes

readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:


0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

status 200: "OK"


404: Page not found

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
14
Loading XML document
//if browser supports XMLHttpRequest
if (window.XMLHttpRequest) { // Create an instance of XMLHttpRequest object.
code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// sets and sends the request for calling "node.xml"
xmlhttp.open("GET","/dom/node.xml",false);
xmlhttp.send();
// sets and returns the content as XML DOM
xmlDoc = xmlhttp.responseXML;
DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
15
Loading xml from String
function loadXMLString(t) { // for non IE browsers
if (window.DOMParser) {
// create an instance for xml dom object parser = new DOMParser();
xmlDoc = parser.parseFromString(t,"text/xml");
}
else { // create an instance for xml dom object
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(t);
}
return xmlDoc;
}
DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
16
Programming Interface
The DOM models XML as a set of node objects.

The nodes can be accessed with JavaScript or other programming languages.

The programming interface to the DOM is defined by a set standard properties


and methods.

Properties are often referred to as something that is (i.e. nodeName is


"book").

Methods are often referred to as something that is done (i.e. delete "book").

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
17
XML DOM Properties
These are some typical DOM properties:

x.nodeName - the name of x

x.nodeValue - the value of x

x.parentNode - the parent node of x

x.childNodes - the child nodes of x

x.attributes - the attributes nodes of x

Note: In the list above, x is a node object.


DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
18
XML DOM Methods
x.getElementsByTagName(name) - get all elements with a
specified tag name

x.appendChild(node) - insert a child node to x

x.removeChild(node) - remove a child node from x

Note: In the list above, x is a node object.

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
19
XML DOM Nodes
According to the XML DOM, everything in an XML document is
a node:

The entire document is a document node

Every XML element is an element node

The text in the XML elements are text nodes

Every attribute is an attribute node

Comments are comment nodes


DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
20
The XML DOM Node Tree

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
21
Node Parents, Children, and Siblings
The nodes in the node tree have a hierarchical relationship
to each other.

The terms parent, child, and sibling are used to describe the
relationships. Parent nodes have children. Children on the
same level are called siblings (brothers or sisters).

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
22
Node relationships
Root

Parent, child, ascendant, descent

nextSibling, previousSibling

First Child - Last Child

etc

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
23
Accessing Nodes
You can access a node in three ways:
◦ 1. By using the getElementsByTagName() method
◦ 2. By looping through (traversing) the nodes tree.
◦ 3. By navigating the node tree, using the node relationships.

getElementsByTagName() Method
◦ Syntax:

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
24
Cont’d …

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
25
DOM List Length
The getElementsByTagName() method returns a node list. A node list is an array of
nodes.

The <title> elements in x can be accessed by index number. To access the third <title>
you can write::
◦ y = x[2];

DOM Node List Length


var x = xmlDoc.getElementsByTagName("title");
for (i = 0; i <x.length; i++) {
  // do something for each node
  }

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
26
Traversing Nodes
The following code loops through the child nodes, that are also element nodes, of the
root node:

txt = "";
x = xmlDoc.documentElement.childNodes;

for (i = 0; i <x.length; i++) {


  // Process only element nodes (type 1)
  if (x[i].nodeType == 1) {
    txt += x[i].nodeName + "<br>";
  }
}
DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
27
Navigating Node Relationships
x = xmlDoc.getElementsByTagName("book")[0];
xlen = x.childNodes.length;
y = x.firstChild;
txt = "";
for (i = 0; i <xlen; i++) {
  // Process only element nodes (type 1)
  if (y.nodeType == 1) {
    txt += y.nodeName + "<br>";
  }
  y = y.nextSibling;
}
DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
28
Node Information
The nodeName, nodeValue, and nodeType properties contain
information about nodes.

Examples: based on the file explained above (book.xml)


◦ Get the node name of an element node

◦ Get the text from a text node

◦ Change the text in a text node

◦ Get the node name and type of an element node

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
29
Node Properties
The nodeName Property
◦ Specifies the name of a node.

◦ nodeName is read-only

◦ nodeName of an element node is the same as the tag name

◦ nodeName of an attribute node is the attribute name

◦ nodeName of a text node is always #text

◦ nodeName of the document node is always #document

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
30
Cont’d …
The nodeValue property
◦ specifies the value of a node.

◦ nodeValue for element nodes is undefined

◦ nodeValue for text nodes is the text itself

◦ nodeValue for attribute nodes is the attribute value

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
31
Get the Value of an Element
The following code retrieves the text node value of the first
<title> element:
◦ var x = xmlDoc.getElementsByTagName("title")
[0].childNodes[0];
var txt = x.nodeValue;

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
32
Change the Value of an Element

The following code changes the text node value of the first
<title> element

var x = xmlDoc.getElementsByTagName("title")
[0].childNodes[0];
x.nodeValue = "Easy Cooking";

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
33
The nodeType Property
The nodeType property specifies the type of node.
nodeType is read only.
The most important node types are:

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
34
DOM Attribute
Returns a list of attribute nodes.

This is called a named node map, and is similar to a node list, except
for some differences in methods and properties.

A attribute list keeps itself up-to-date. If an attribute is deleted or


added, the list is automatically updated.

This code fragment returns a list of attribute nodes from the first
<book> element in "books.xml":
DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
35
Cont’d …
x = xmlDoc.getElementsByTagName('book')
[0].attributes;

After the execution of the code above, x.length


= is the number of attributes and
x.getNamedItem() can be used to return an
attribute node.
DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
36
Attribute Length

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
37
Get the Value of an Attribute
The way to get the value of an attribute, is to get its text
value.

This can be done using the getAttribute() method or using


the nodeValue property of the attribute node.

The getAttribute() method returns an attribute's value.


 x = xmlDoc.getElementsByTagName("title")[0];
txt = x.getAttribute("lang");

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
38
Get an Attribute Value - getAttributeNode()
x = xmlDoc.getElementsByTagName("title")[0];
y = x.getAttributeNode("lang");
txt = y.nodeValue;

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
39
XML Document Object Model-Part 2
CH AN G E , R EMO V E, RE PLA CE AN D AD D N EW N O D ES

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
40
XML DOM Change Node Values
The nodeValue property is used to change a node value.

The setAttribute() method is used to change an attribute value.

Change the Value of an Element


◦ The way to change the text of an element, is to change the value of the
child node (text node).
◦ The nodeValue property can be used to change the value of a text node.

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
41
Cont’d …
Example
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
42
Change the Value of an Attribute
Unlike element nodes, attribute nodes have text values.

The way to change the value of an attribute, is to change its text value.

This can be done using the setAttribute() method or using the


nodeValue property of the attribute node.

Examples: using setAttribute()


◦ xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("category","food");

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
43
Cont’d …
Using nodeValue
◦ xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0]
y=x.getAttributeNode("category");
y.nodeValue="food";

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
44
XML DOM Remove Nodes
Remove an Element Node
◦ The removeChild() method removes a specified node.

◦ When a node is removed, all its child nodes are also removed.

Example:
◦ xmlDoc=loadXMLDoc("books.xml");
y=xmlDoc.getElementsByTagName("book")[0];
xmlDoc.documentElement.removeChild(y);

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
45
Remove Myself - Remove the Current Node
The removeChild() method is the only way to remove a specified
node.

It is possible to remove that node using the parentNode property


and the removeChild() method:

Example
◦ xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0];
x.parentNode.removeChild(x);
DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
46
Remove a Text Node
The removeChild() method can also be used to remove a
text node:

Example
◦ xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];
x.removeChild(y);

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
47
Clear a Text Node

The nodeValue property can be used to change or


clear the value of a text node:

Example
◦ xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="";

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
48
Remove an Attribute Node by Name
The removeAttribute(name) method is used to remove an
attribute node by its name.

Example: removeAttribute('category')

Example
◦ xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book");
x[0].removeAttribute("category");

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
49
Replace Nodes: Replace an Element Node
The replaceChild(newNode, oldNode) method is used to replace a node.

Example
◦ xmlDoc=loadXMLDoc("books.xml");

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");

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
50
Cont’d …
//add the 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 node
x.replaceChild(newNode,y);

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
51
Replace Data In a Text Node
The replaceData(offset, length, string) method is used to
replace data in a text node.

The replaceData() method has three parameters:


◦ offset - Where to begin replacing characters. Offset value

starts at zero

◦ length - How many characters to replace

◦ string - The string to insert


DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
52
Cont’d …
Example

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")
[0].childNodes[0];
x.replaceData(0,8,"Easy");

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
53
Use the nodeValue Property Instead
It is easier to replace the data in a text node using the
nodeValue property.

◦ xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Italian";

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
54
Create Nodes: Create a New Element Node
The createElement(eleName) method creates a new element node:

Example
◦ xmlDoc=loadXMLDoc("books.xml");

newel=xmlDoc.createElement("edition");

x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
55
Create a New Attribute Node
The createAttribute() is used to create a new attribute node:

Example
◦ xmlDoc=loadXMLDoc("books.xml");

newatt=xmlDoc.createAttribute("edition");
newatt.nodeValue="first";

x=xmlDoc.getElementsByTagName("title");
x[0].setAttributeNode(newatt);
DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
56
Create an Attribute Using setAttribute()
Since the setAttribute() method creates a new attribute if the
attribute does not exist, it can be used to create a new attribute.

Example
◦ xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("edition","first");

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
57
Create a Text Node
Example

xmlDoc=loadXMLDoc("books.xml");

newel=xmlDoc.createElement("edition");
newtext=xmlDoc.createTextNode("first");
newel.appendChild(newtext);

x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);
DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
58
XML DOM Add Nodes
Add a Node - appendChild()
◦ The appendChild() method adds a child node to an existing node.

◦ The new node is added (appended) after any existing child nodes.

◦ Note: Use insertBefore() if the position of the node is important.

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
59
Cont’d …
Example

xmlDoc=loadXMLDoc("books.xml");
newel=xmlDoc.createElement("edition");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
60
Insert a Node - insertBefore()
The insertBefore() method is used to insert a node before a specified child
node.

This method is useful when the position of the added node is important:

Example
◦ xmlDoc=loadXMLDoc("books.xml");
newNode=xmlDoc.createElement("book");
x=xmlDoc.documentElement;
y=xmlDoc.getElementsByTagName("book")[3];
x.insertBefore(newNode,y);
DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
61
Add a New Attribute
There is no method called addAtribute().

The setAttribute() method creates a new attribute if the attribute


does not exist:

Example
◦ xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("edition","first");
DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML
02/16/2023
DOM
62
Add Text to a Text Node - insertData()
The insertData() method inserts data into an existing text node.

It has two parameters:


◦ offset - Where to begin inserting characters (starts at zero)

◦ string - The string to insert

Example
◦ xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.insertData(0,"Easy ");

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
63
Clone Nodes
The cloneNode() method creates a copy of a specified node.

The cloneNode() method has a parameter (true or false). This


parameter indicates if the cloned node should include all
attributes and child nodes of the original node.

The following code fragment copies the first <book> node and
appends it to the root node of the document:

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
64
Cont’d …
Example
xmlDoc=loadXMLDoc("books.xml");

oldNode=xmlDoc.getElementsByTagName('book')[0];
newNode=oldNode.cloneNode(true);
xmlDoc.documentElement.appendChild(newNode);

//Output all titles


y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++)
{
document.write(y[i].childNodes[0].nodeValue);
document.write("<br />");
}

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
65
Thank you!

QUESTIONS?

DIOT, INTEGRATIVE PROGRAMMING AND TECHNOLOGIES, XML


02/16/2023
DOM
66

You might also like