Vous êtes sur la page 1sur 64

XML DOM TUTORIAL

XML DOM Introduction


The XML DOM defines a standard for accessing and manipulating XML.

What You Should Already Know


Before you continue you should have a basic understanding of the following:
 HTML
 XML
 JavaScript

What is the DOM?


The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents like XML and HTML:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs
and scripts to dynamically access and update the content, structure, and style of a document."
The DOM is separated into 3 different parts / levels:
Core DOM - standard model for any structured document
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
The DOM defines the objects and properties of all document elements, and the methods (interface) to
access them.

What is the HTML DOM?


The HTML DOM defines the objects and properties of all HTML elements, and the methods (interface) to
access them.
If you want to study the HTML DOM, find the HTML DOM tutorial on our homepage.

What is the XML DOM?


The XML DOM is:
A standard object model for XML
A standard programming interface for XML
Platform- and language-independent
A W3C standard
The XML DOM defines the objects and properties of all XML elements, and the methods (interface) to
access them.

In other words:
The XML DOM is a standard for how to get, change, add, or delete XML elements.

XML DOM Nodes


In the DOM, everything in an XML document is a node.

DOM Nodes
According to the DOM, everything in an XML document is a node.

The DOM says:


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

DOM Example
Look at the following XML file (books.xml):
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>

1
<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>

The root node in the XML above is named <bookstore>. All other nodes in the document are contained
within <bookstore>.
The root node <bookstore> holds four <book> nodes.
The first <book> node holds four nodes: <title>, <author>, <year>, and <price>, which contains one text
node each, "Everyday Italian", "Giada De Laurentiis", "2005", and "30.00".
Text is Always Stored in Text Nodes
A common error in DOM processing is to expect an element node to contain text.
However, the text of an element node is stored in a text node.

In this example:
<year>2005</year>, the element node <year>, holds a text node with the value "2005".
"2005" is not the value of the <year> element!

XML DOM Node Tree


The XML DOM views an XML document as a node-tree.
All the nodes in the tree have a relationship to each other.

The XML DOM Node Tree


The XML DOM views an XML document as a tree-structure. The tree structure is called a node-tree.
All nodes can be accessed through the tree. Their contents can be modified or deleted, and new elements
can be created.
The node tree shows the set of nodes, and the connections between them. The tree starts at the root node
and branches out to the text nodes at the lowest level of the tree:

2
The image above represents the XML file books.xml.
books.xml>Everyday Italian Giada De Laurentiis 2005 30.00 Harry Potter J K. Rowling 2005 29.99 XQuery
Kick Start James McGovern Per Bothner Kurt Cagle James Linn Vaidyanathan Nagarajan 2003 49.99
Learning XML Erik T. Ray 2003 39.95

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).
In a node tree, the top node is called the root
Every node, except the root, has exactly one parent node
A node can have any number of children
A leaf is a node with no children
Siblings are nodes with the same parent
The following image illustrates a part of the node tree and the relationship between the nodes:

Because the XML data is structured in a tree form, it can be traversed without knowing the exact structure of
the tree and without knowing the type of data contained within.

3
First Child - Last Child
Look at the following XML fragment:<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>

In the XML above, the <title> element is the first child of the <book> element, and the <price> element is the
last child of the <book> element.
Furthermore, the <book> element is the parent node of the <title>, <author>, <year>, and <price> elements.

Parsing the XML DOM


Most browsers have a build-in XML parser to read and manipulate XML.
The parser converts XML into a JavaScript accessible object.

Examples
W3Schools examples are browser and platform independent. These examples work in all modern browsers.

 Load and parse an XML file


<html>
<body>
<script type="text/javascript">
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc=document.implementation.createDocument("","",null);
}
catch(e) {alert(e.message)}
}
try
{
xmlDoc.async=false;
xmlDoc.load("books.xml");
document.write("xmlDoc is loaded, ready for use");
}
catch(e) {alert(e.message)}
</script>
</body>
</html>

Result:
xmlDoc is loaded, ready for use

 Load and parse an XML string


<html>
<body>
<script type="text/javascript">
text="<bookstore>"
text=text+"<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";

4
text=text+"</book>";
text=text+"</bookstore>";

try //Internet Explorer


{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(text);
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
catch(e) {alert(e.message)}
}
try
{
document.write("xmlDoc is loaded, ready for use");
}
catch(e) {alert(e.message)}
</script>
</body>
</html>

Result:
xmlDoc is loaded, ready for use

Parsing XML
All modern browsers have a build-in XML parser that can be used to read and manipulate XML.
The parser reads XML into memory and converts it into an XML DOM object that can be accesses with
JavaScript.
There are some differences between Microsoft's XML parser and the parsers used in other browsers. The
Microsoft parser supports loading of both XML files and XML strings (text), while other browsers use
separate parsers. However, all parsers contain functions to traverse XML trees, access, insert, and delete
nodes.
In this tutorial we will show you how to create scripts that will work in both Internet Explorer and other
browsers.

Loading XML with Microsoft's XML Parser


Microsoft's XML parser is built into Internet Explorer 5 and higher.
The following JavaScript fragment loads an XML document ("books.xml") into the parser:xmlDoc=new
ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load("books.xml");

Code explained:
The first line creates an empty Microsoft XML document object.
The second line turns off asynchronized loading, to make sure that the parser will not continue execution of
the script before the document is fully loaded.
The third line tells the parser to load an XML document called "books.xml".
The following JavaScript fragment loads a string called txt into the parser:xmlDoc=new
ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(txt);
Note: The loadXML() method is used for loading strings (text), load() is used for loading files.

5
XML Parser in Firefox and Other Browsers
The following JavaScript fragment loads an XML document ("books.xml") into the
parser:xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.async="false";
xmlDoc.load("books.xml");

Code explained:
The first line creates an empty XML document object.
The second line turns off asynchronized loading, to make sure that the parser will not continue execution of
the script before the document is fully loaded.
The third line tells the parser to load an XML document called "books.xml".
The following JavaScript fragment loads a string called txt into the parser:parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");

Code explained:
The first line creates an empty XML document object.
The second line tells the parser to load a string called txt.

Note: Internet Explorer uses the loadXML() method to parse an XML string, while other browsers uses the
DOMParser object.
Parsing an XML File - A Cross browser Example

The following example loads an XML document ("books.xml") into the XML parser:Example<html>
<body>
<script type="text/javascript">
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc=document.implementation.createDocument("","",null);
}
catch(e) {alert(e.message)}
}
try
{
xmlDoc.async=false;
xmlDoc.load("books.xml");
document.write("xmlDoc is loaded, ready for use");
}
catch(e) {alert(e.message)}
</script>
</body>
</html>

Error: Access Across Domains


For security reasons, modern browsers does not allow access across domains.
This means, that both the web page and the XML file it tries to load, must be located on the same server.
The examples on W3Schools all open XML files located on the W3Schools domain.
If you want to use the example above on one of your web pages, the XML files you load must be located on
your own server. Otherwise the xmlDoc.load() method, will generate the error "Access is denied".

Parsing an XML String - A Cross browser Example


The following code loads and parses an XML string:Example
<html>
<body>
<script type="text/javascript">
text="<bookstore>"
text=text+"<book>";

6
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
text=text+"</bookstore>";

try //Internet Explorer


{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(text);
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
catch(e) {alert(e.message)}
}
document.write("xmlDoc is loaded, ready for use");
</script>
</body>
</html>

Note: Internet Explorer uses the loadXML() method to parse an XML string, while other browsers uses the
DOMParser object.

XML DOM Load Function


The code for loading XML documents can be stored in a function.
The function described below, is used in all examples in this tutorial.

An XML Load Function - loadXMLDoc()


The XML DOM contains methods (functions) to traverse XML trees, access, insert, and delete nodes.
However, before an XML document can be accessed and manipulated, it must be loaded into an XML DOM
object.
The previous chapter demonstrated how to load XML documents. To make it simpler to maintain this code, it
should be written as a function: Examplefunction loadXMLDoc(dname)
{
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc=document.implementation.createDocument("","",null);
}
catch(e) {alert(e.message)}
}
try
{
xmlDoc.async=false;
xmlDoc.load(dname);
return(xmlDoc);
}
catch(e) {alert(e.message)}
return(null);
}

7
The function above can be stored in the <head> section of an HTML page, and called from a script in the
page.

An External Load Function


To make the function above even easier to maintain, and to make sure the same code is used in all pages, it
can be stored in an external file.
We have called the file "loadxmldoc.js"
The file can be loaded in the <head> section of an HTML page, and loadXMLDoc() can be called from a
script in the page:Example<html>
<head>
<script type="text/javascript" src="loadxmldoc.js">
</script>
</head>
<body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
document.write("xmlDoc is loaded, ready for use");
</script>
</body>
</html>

An XML Load Function - loadXMLString()


A similar function can be used to load an XML string (instead an XML file):function loadXMLString(txt)
{
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(txt);
return(xmlDoc);
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
return(xmlDoc);
}
catch(e) {alert(e.message)}
}
return(null);
}

To make the function above easier to maintain, and to make sure the same code is used in all pages, it can
be stored in an external file.
We have stored in in a file called "loadxmlstring.js".

XML DOM - Properties and Methods


Properties and methods define the programming interface to the XML DOM.

Examples
The examples below use the XML file books.xml.
A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.
A function, loadXMLString(), in an external JavaScript is used to load the XML string.

 Load and parse an XML file


<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>

8
</head>
<body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeValue);
</script>
</body>
</html>

Result:
Everyday Italian
Giada De Laurentiis
2005
 Load and parse an XML string
<html>
<head>
<script type="text/javascript" src="loadxmlstring.js"></script>
</head>
<body>
<script type="text/javascript">
text="<bookstore>"
text=text+"<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
text=text+"</bookstore>";

xmlDoc=loadXMLString(text);

document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeValue);
</script>
</body>
</html>

Result:
Everyday Italian
Giada De Laurentiis
2005

Programming Interface
The DOM models XML as a set of node objects. The nodes can be accessed with JavaScript or other
programming languages. In this tutorial we use JavaScript.
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").

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

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

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.

Example
The JavaScript code to get the text from the first <title> element in books.xml:
txt=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue
After the execution of the statement, txt will hold the value "Everyday Italian"

Explained:
xmlDoc - the XML DOM object created by the parser.
getElementsByTagName("title")[0] - the first <title> element
childNodes[0] - the first child of the <title> element (the text node)
nodeValue - the value of the node (the text itself)

In the example above, getElementsByTagName is a method, while childNodes and nodeValue are
properties.

Parsing an XML File - A Cross browser Example


The following code fragment uses the loadXMLDoc function (described in the previous chapter) to load
books.xml into the XML parser, and displays data from the first
book:ExamplexmlDoc=loadXMLDoc("books.xml");
document.write(xmlDoc.getElementsByTagName("title")
[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("author")
[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("year")
[0].childNodes[0].nodeValue);

Output:
Everyday Italian
Giada De Laurentiis
2005

In the example above we use childNodes[0] for each text node, even if there is only one text node for each
element. This is because the getElementsByTagName() method always returns an array.

Parsing an XML String - A Cross browser Example


The following code loads and parses an XML string:
The following code fragment uses the loadXMLString function (described in the previous chapter) to load
books.xml into the XML parser, and displays data from the first book:Exampletext="<bookstore>"
text=text+"<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
text=text+"</bookstore>";
xmlDoc=loadXMLString(text);
document.write(xmlDoc.getElementsByTagName("title")
[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("author")
[0].childNodes[0].nodeValue);
document.write("<br />");

10
document.write(xmlDoc.getElementsByTagName("year")
[0].childNodes[0].nodeValue);

Output:
Everyday Italian
Giada De Laurentiis
2005

XML DOM - Accessing Nodes


With the DOM, you can access every node in an XML document.

Examples
The examples below use the XML file books.xml.
A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.
 Access a node using its index number in a node list
This example uses the getElementsByTagname() method to get the third <title> element in "books.xml"

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head>
<body>

<script type="text/javascript">

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title");
document.write(x[2].childNodes[0].nodeValue);

</script>
</body>
</html>

Result:
XQuery Kick Start
 Loop through nodes using the length property
This example uses the length property to loop through all <title> elements in "books.xml"

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head>
<body>

<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

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

Result:
Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML

11
 See the node type of an element
This example uses the nodeType property to get node type of the root element in "books.xml".

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head>
<body>

<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

document.write(xmlDoc.documentElement.nodeName);
document.write("<br />");
document.write(xmlDoc.documentElement.nodeType);
</script>
</body>
</html>

Result:
bookstore
1

 Loop through element nodes


This example uses the nodeType property to only process element nodes in "books.xml".

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head>
<body>

<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{
if (x[i].nodeType==1)
{//Process only element nodes (type 1)
document.write(x[i].nodeName);
document.write("<br />");
}
}
</script>
</body>
</html>

Result:
book
book
book
book

 Loop through element nodes using node realtionships


This example uses the nodeType property and the nextSibling property to process element nodes in
"books.xml".

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>

12
</head>
<body>

<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book")[0].childNodes;
y=xmlDoc.getElementsByTagName("book")[0].firstChild;
for (i=0;i<x.length;i++)
{
if (y.nodeType==1)
{//Process only element nodes (type 1)
document.write(y.nodeName + "<br />");
}
y=y.nextSibling;
}
</script>
</body>
</html>

Result:
title
author
year
price

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.
The getElementsByTagName() Method

getElementsByTagName() returns all elements with a specified tag name.


Syntaxnode.getElementsByTagName("tagname");

Example
The following example returns all <title> elements under the x element:x.getElementsByTagName("title");
Note that the example above only returns <title> elements under the x node. To return all <title> elements in
the XML document use: xmlDoc.getElementsByTagName("title");
where xmlDoc is the document itself (document node).

DOM Node List


The getElementsByTagName() method returns a node list. A node list is an array of nodes.
The following code loads "books.xml" into xmlDoc using loadXMLDoc() and stores a list of <title> nodes (a
node list) in the variable x:xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title");
The <title> elements in x can be accessed by index number. To access the third <title> you can
write:Exampley=x[2];

Note: The index starts at 0.


You will learn more about node lists in a later chapter of this tutorial.

DOM Node List Length


The length property defines the length of a node list (the number of nodes).
You can loop through a node list by using the length property:ExamplexmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title");

for (i=0;i<x.length;i++)
{
document.write(x[i].childNodes[0].nodeValue);

13
document.write("<br />");
}

Example explained:
Load "books.xml" into xmlDoc using loadXMLDoc()
Get all <title> element nodes
For each title element, output the value of its text node

Node Types
The documentElement property of the XML document is the root node.
The nodeName property of a node is the name of the node.
The nodeType property of a node is the type of the node.
You will learn more about the node properties in the next chapter of this tutorial.

Traversing Nodes
The following code loops through the child nodes, that are also element nodes, of the root
node:ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{
if (x[i].nodeType==1)
{//Process only element nodes (type 1)
document.write(x[i].nodeName);
document.write("<br />");
}
}

Example explained:
Load "books.xml" into xmlDoc using loadXMLDoc()
Get the child nodes of the root element
For each child node, check the node type of the node. If the node type is "1" it is an element node
Output the name of the node if it is an element node

Navigating Node Relationships


The following code navigates the node tree using the node
relationships:ExamplexmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book")[0].childNodes;
y=xmlDoc.getElementsByTagName("book")[0].firstChild;

for (i=0;i<x.length;i++)
{
if (y.nodeType==1)
{//Process only element nodes (type 1)
document.write(y.nodeName + "<br />");
}
y=y.nextSibling;
}

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Get the child nodes of the first book element
3. Set the "y" variable to be the first child node of the first book element
4. For each child node (starting with the first child node "y"):
5. Check the node type. If the node type is "1" it is an element node
6. Output the name of the node if it is an element node
7. Set the "y" variable to be the next sibling node, and run through the loop again

XML DOM Node Information


The node properties: nodeName, nodeValue, and nodeType.
Examples

14
The examples below use the XML file books.xml.
A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

 Get the node name of an element node


This example uses the nodeName property to get the node name of the root element in "books.xml".

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head>
<body>

<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

document.write(xmlDoc.documentElement.nodeName);
</script>
</body>
</html>

Result:
bookstore
 Get the text from a text node
This example uses the nodeValue property to get the text of the first <title> element in "books.xml".

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head>
<body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
txt=x.nodeValue;
document.write(txt);
</script>
</body>
</html>

Result:
Everyday Italian

 Change the text in a text node


This example uses the nodeValue property to change the text of the first <title> element in "books.xml".

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head>
<body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
txt=x.nodeValue;
document.write(txt);
</script>
</body>
</html>

15
Result:
Easy Cooking

 Get the node name and type of an element node


This example uses the nodeName and nodeType property to get node name and type of the root element in
"books.xml".

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head>
<body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
document.write(xmlDoc.documentElement.nodeName);
document.write("<br />");
document.write(xmlDoc.documentElement.nodeType);
</script>
</body>
</html>

Result:
bookstore
1

Node Properties
In the XML Document Object Model (DOM), each node is an object.
Objects have methods (functions) and properties (information about the object), that can be accessed and
manipulated by JavaScript.

Three important XML DOM node properties are:


 nodeName
 nodeValue
 nodeType

The nodeName Property


 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

The nodeValue Property


 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

Example1: Get the Value of an Element


The following code retrieves the text node value of the first <title>
element:ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
txt=x.nodeValue;

Result:
txt = "Everyday Italian"

Example explained:
Load "books.xml" into xmlDoc using loadXMLDoc()
Get text node of the first <title> element node

16
Set the txt variable to be the value of the text node

Example 2: Change the Value of an Element


The following code changes the text node value of the first <title>
element:ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";

Example explained:
Load "books.xml" into xmlDoc using loadXMLDoc()
Get text node of the first <title> element node
Change the value of the text node to "Easy Cooking"
 The nodeType Property
 The nodeType property specifies the type of node.
 nodeType is read only.

The most important node types are:


Node type NodeType
Element 1
Attribute 2
Text 3
Comment 8
Document 9

XML DOM Node List


A list of nodes is returned by the getElementsByTagName() method and the childNodes property.

Examples
The examples below use the XML file books.xml.
A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

 Get the text from the first <title> element


This example uses the getElementsByTagName() method to get the text from the first <title> element in
"books.xml".

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js">
</script>
</head>
<body>

<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title");
txt=x[0].childNodes[0].nodeValue;
document.write(txt);
</script>
</body>
</html>

Result:
Everyday Italian

 Loop through nodes using the length property


This example uses node list and the length property to loop through all <title> elements in "books.xml"

17
<html>
<head>
<script type="text/javascript" src="loadxmldoc.js">
</script>
</head>
<body>

<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

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

Result:
Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML

 Get the attribute of an element


This example uses a attribute list to get attribute from the first <book> element in "books.xml".
<html>
<head>
<script type="text/javascript" src="loadxmldoc.js">
</script>
</head>
<body>

<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book")[0].attributes;
document.write(x.getNamedItem("category").nodeValue);
document.write("<br />" + x.length);
</script>
</body>
</html>

Result:
cooking
1

DOM Node List


When using properties or methods like childNodes or getElementsByTagName(), a node list object is
returned.
 A node list object represents a list of nodes, in the same order as in the XML.
 Nodes in the node list are accessed with index numbers starting from 0.

18
The following image represents a node list of the <title> elements in "books.xml":

The following code fragment loads "books.xml" into xmlDoc using loadXMLDoc() and returns a node list of
title elements in "books.xml":xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title");
After the execution of the statement above, x is a node list object.
The following code fragment returns the text from the first <title> element in the node list
(x):Exampletxt=x[0].childNodes[0].nodeValue;
After the execution of the statement above, txt = "Everyday Italian".

Node List Length


A node list object keeps itself up-to-date. If an element is deleted or added, the list is automatically updated.
The length property of a node list is the number of nodes in the list.
The following code fragment loads "books.xml" into xmlDoc using loadXMLDoc() and returns the number of
<title> elements in "books.xml":xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('title').length;
After the execution of the statement above, x = 4.
The length of the node list can be used to loop through all the elements in the list.
The following code fragment uses the length property to loop through the list of <title>
elements:ExamplexmlDoc=loadXMLDoc("books.xml");

//the x variable will hold a node list


x=xmlDoc.getElementsByTagName('title');

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

Output:
Everyday Italian

19
Harry Potter
XQuery Kick Start
Learning XML

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Set the x variable to hold a node list of all title elements
3. Output the value from the text node of all <title> elements
4. DOM Attribute List (Named Node Map)

The attributes property of an element node 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.
The following code fragment loads "books.xml" into xmlDoc using loadXMLDoc() and returns a list of
attribute nodes from the first <book> element in "books.xml":xmlDoc=loadXMLDoc("books.xml");
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.
The following code fragment displays the value of the "category" attribute, and the number of attributes, of a
book:ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0].attributes;
document.write(x.getNamedItem("category").nodeValue);
document.write("<br />" + x.length);

Output:
cooking
1

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Set the x variable to hold a list of all attributes of the first <book> element
3. Output the value from the "category" attribute
4. Output the length of the attribute list

XML DOM Traverse Node Tree


Traversing means looping through or traveling across the node tree.

Examples
The examples below use the XML file books.xml.
A function, loadXMLString(), in an external JavaScript is used to load the XML string.

Traverse a node tree


Loop through all child nodes of the <book> element

Traversing the Node Tree


Often you want to loop an XML document, for example: when you want to extract the value of each element.
This is called "Traversing the node tree"
The example below loops through all child nodes of <book>, and displays their names and
values:Example<html>
<head>
<script type="text/javascript" src="loadxmlstring.js"></script>
</head>
<body>
<script type="text/javascript">
text="<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
xmlDoc=loadXMLString(text);

20
// documentElement always represents the root node
x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{
document.write(x[i].nodeName);
document.write(": ");
document.write(x[i].childNodes[0].nodeValue);
document.write("<br />");
}
</script>
</body>
</html>

Output:
title: Everyday Italian
author: Giada De Laurentiis
year: 2005

Example explained:
1. loadXMLString() loads the XML string into xmlDoc
2. Get the child nodes of the root element
3. For each child node, output the node name and the node value of the text node

XML DOM Browser Differences


Different browsers handle empty text nodes in the XML DOM differently.

Examples
The examples below use the XML file books.xml.
A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

 Display the length of a node list


This example shows the length of a node list. The result is different in Internet Explorer and other browsers

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head>
<body>

<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.documentElement.childNodes;
document.write("Number of child nodes: " + x.length);
</script>
</body>
</html>

Result:
Number of child nodes: 9

 Ignore empty text between nodes


This example checks the nodeType of the nodes and only processes element nodes

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head>
<body>

21
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{
if (x[i].nodeType==1)
{
document.write(x[i].nodeName);
document.write("<br />");
}
}
</script>
</body>
</html>

Result:
book
book
book
book

Browser Differences in DOM Parsing


All modern browsers support the W3C DOM specification.
However, there are some differences between browsers. Two important differences are:
The way they load XML
The way they handle white-spaces and new lines
The different ways to load XML is explained in the chapter "DOM Parser".
The different ways to handle white spaces and new lines is explained in this chapter.

DOM - White Spaces and New Lines


XML often contains new line, or white space characters, between nodes. This is often the case when the
document is edited by a simple editor like Notepad.
The following example (edited by Notepad) contains CR/LF (new line) between each line and two spaces in
front of each child node: <book>
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>

Firefox, and some other browsers, will treat empty white-spaces or new lines as text nodes, Internet
Explorer will not
The following code fragment displays how many child nodes the root element (of books.xml)
has:ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.documentElement.childNodes;
document.write("Number of child nodes: " + x.length);

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Get the child nodes of the root element
3. Output the number of child nodes. The result is different depending on which browser you use.
Firefox will alert 9 child nodes, while Internet Explorer will alert 4.
4. Ignore Empty Text Between Elements

To ignore empty text nodes between element nodes, you can check the node type. An element node has
type 1:ExamplexmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.documentElement.childNodes;

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

22
{
if (x[i].nodeType==1)
{// only process element nodes
document.write(x[i].nodeName);
document.write("<br />");
}
}
Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Get the child nodes of the root element
3. For each child node, check the node type of the node. If the node type is "1" it is an element node
4. Output the name of the node if it is an element node

XML DOM - Navigating Nodes


Nodes can be navigated using node relationships.

Examples
The examples below use the XML file books.xml.
A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.
 Get the parent of a node
This example uses the parentNode property to get the parent of a node

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js">
</script>
</head>
<body>

<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book")[0];
document.write(x.parentNode.nodeName);
</script>
</body>
</html>

Result:
bookstore
 Get the first child element of a node
This example uses the firstChild() method and a custom function to get the first child node of a node

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js">
</script>
<script type="text/javascript">
//check if the first node is an element node
function get_firstChild(n)
{
y=n.firstChild;
while (y.nodeType!=1)
{
y=y.nextSibling;
}
return y;
}
</script>

23
</head>
<body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
x=get_firstChild(xmlDoc.getElementsByTagName("book")[0]);
document.write(x.nodeName);
</script>
</body>
</html>

Result:
title

Navigating DOM Nodes


Accessing nodes in the node tree via the relationship between nodes, is often called "navigating nodes".
In the XML DOM, node relationships are defined as properties to the nodes:
 parentNode
 childNodes
 firstChild
 lastChild
 nextSibling
 previousSibling
The following image illustrates a part of the node tree and the relationship between nodes in books.xml:

DOM - Parent Node


All nodes has exactly one parent node. The following code navigates to the parent node of <book>:
ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0];
document.write(x.parentNode.nodeName);

Example explained:

24
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Get the first <book> element
3. Output the node name of the parent node of "x"
4. Avoid Empty Text Nodes

Firefox, and some other browsers, will treat empty white-spaces or new lines as text nodes, Internet
Explorer will not.
This causes a problem when using the properties: firstChild, lastChild, nextSibling, previousSibling.
To avoid navigating to empty text nodes (spaces and new-line characters between element nodes), we use
a function that checks the node type:function get_nextSibling(n)
{
y=n.nextSibling;
while (y.nodeType!=1)
{
y=y.nextSibling;
}
return y;
}

The function above allows you to use get_nextSibling(node) instead of the property node.nextSibling.

Code explained:
Element nodes are type 1. If the sibling node is not an element node, it moves to the next nodes until an
element node is found. This way, the result will be the same in both Internet Explorer and Firefox.

Get the First Child Element


The following code displays the first element node of the first <book>:Example<html>
<head>
<script type="text/javascript" src="loadxmldoc.js">
</script>
<script type="text/javascript">
//check if the first node is an element node
function get_firstChild(n)
{
y=n.firstChild;
while (y.nodeType!=1)
{
y=y.nextSibling;
}
return y;
}
</script>
</head>
<body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

x=get_firstChild(xmlDoc.getElementsByTagName("book")[0]);
document.write(x.nodeName);
</script>
</body>
</html>

Output:
title

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Use the get_firstChild fucntion on the first <book> element node to get the first child node that is an
element node
3. Output the node name of first child node that is an element node

25
XML DOM Get Node Values
The nodeValue property is used to get the text value of a node.
The getAttribute() method returns the value of an attribute.

Examples
The examples below use the XML file books.xml.
A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

 Get an element's value


This example uses the getElementsByTagname() method to get the first <title> element in "books.xml"

<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head>
<body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

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

</script>
</body>
</html>

Result:
Everyday Italian

Get the Value of an Element


In the DOM, everything is a node. Element nodes does not have a text value.
The text of an element node is stored in a child node. This node is called a text node.
The way to get the text of an element, is to get the value of the child node (text node).
Get an Element Value

The getElementsByTagName() method returns a node list containing all elements with the specified tag
name in the same order as they appear in the source document.
The following code loads "books.xml" into xmlDoc using loadXMLDoc() and retrieves the first <title>
element:xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0];
The childNodes property returns a list of child nodes. The <title> element has only one child node. It is a text
node.
The following code retrieves the text node of the <title> element:x=xmlDoc.getElementsByTagName("title")
[0];
y=x.childNodes[0];
The nodeValue property returns the text value of the text
node:Examplex=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];
txt=y.nodeValue;

Result:
txt = "Everyday Italian"

Loop through all <title> elements:


Get the Value of an Attribute
In the DOM, attributes are nodes. Unlike element nodes, attribute nodes have text values.
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.

Get an Attribute Value - getAttribute()


The getAttribute() method returns an attribute value.

26
The following code retrieves the text value of the "lang" attribute of the first <title>
element:ExamplexmlDoc=loadXMLDoc("books.xml");
txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");

Result:
txt = "en"

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Set the txt variable to be the value of the "lang" attribute of the first title element node
3. Loop through all <book> elements and get their "category" attributes: Try it yourself
4. Get an Attribute Value - getAttributeNode()

The getAttributeNode() method returns an attribute node.


The following code retrieves the text value of the "lang" attribute of the first <title>
element:ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].getAttributeNode("lang");
txt=x.nodeValue;

Result:
txt = "en"

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Get the "lang" attribute node of the first <title> element node
3. Set the txt variable to be the value of the attribute

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


In the DOM, everything is a node. Element nodes does not have a text value.
The text of an element node is stored in a child node. This node is called a text node.
The way to change the text of an element, is to change the value of the child node (text node).

Change the Value of a Text Node


The nodeValue property can be used to change the value of a text node.
The following code changes the text node value of the first <title>
element:ExamplexmlDoc=loadXMLDoc("books.xml");

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

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Get the text node of the first <title> element
3. Change the node value of the text node to "Easy Cooking"
Loop through and change the text node of all <title> elements:

Change the Value of an Attribute


In the DOM, attributes are nodes. 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.

Change an Attribute Using setAttribute()


The setAttribute() method changes the value of an existing attribute, or creates a new attribute.
The following code changes the category attribute of the <book>
element:ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("category","food");

27
Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Get the first <book> element
3. Change the "category" attribute value to "food"

Loop through all <title> elements and add a new attribute:


Note: If the attribute does not exist, a new attribute is created (with the name and value specified).
Change an Attribute Using nodeValue
The nodeValue property can be used to change the value of a attribute
node:ExamplexmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book")[0]
y=x.getAttributeNode("category");
y.nodeValue="food";

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Get the "category" attribute of the first <book> element
3. Change the attribute node value to "food"

XML DOM Remove Nodes


The removeChild() method removes a specified node.
The removeAttribute() method removes a specified attribute.

*Remove an Element Node


The removeChild() method removes a specified node.
When a node is removed, all its child nodes are also removed.
The following code fragment will remove the first <book> element from the loaded xml:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
document.write("Number of book nodes: ");
document.write(xmlDoc.getElementsByTagName('book').length);
document.write("<br />");
y=xmlDoc.getElementsByTagName("book")[0];
xmlDoc.documentElement.removeChild(y);
document.write("Number of book nodes after removeChild(): ");
document.write(xmlDoc.getElementsByTagName('book').length);
</script></body></html>

Result:
Number of book nodes: 4
Number of book nodes after removeChild(): 3

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Set the variable y to be the element node to remove
3. Remove the element node by using the removeChild() method from the parent node
4. Remove Myself - Remove the Current Node
The removeChild() method is the only way to removes a specified node.
When you have navigated to the node you want to remove, it is possible to remove that node using the
parentNode property and the removeChild() method:ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0];
x.parentNode.removeChild(x);

<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script>

28
</head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
document.write("Number of book nodes before removeChild(): ");
document.write(xmlDoc.getElementsByTagName("book").length);
document.write("<br />");
x=xmlDoc.getElementsByTagName("book")[0]
x.parentNode.removeChild(x);
document.write("Number of book nodes after removeChild(): ");
document.write(xmlDoc.getElementsByTagName("book").length);
</script></body> </html>

Result:
Number of book nodes before removeChild(): 4
Number of book nodes after removeChild(): 3

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Set the variable y to be the element node to remove
3. Remove the element node by using the parentNode property and the removeChild() method

*Remove a Text Node


The removeChild() method can also be used to remove a text node: <html>
<head>
<script type="text/javascript" src="loadxmldoc.js">
</script>
</head>
<body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0];
document.write("Child nodes: ");
document.write(x.childNodes.length);
document.write("<br />");
y=x.childNodes[0];
x.removeChild(y);
document.write("Child nodes: ");
document.write(x.childNodes.length);
</script>
</body>
</html>

Result:
Child nodes: 1
Child nodes: 0

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Set the variable x to be the first title element node
3. Set the variable y to be the text node to remove
4. Remove the element node by using the removeChild() method from the parent node

It is not very common to use removeChild() just to remove the text from a node. The nodeValue property can
be used instead. See next paragraph.

*Clear a Text Node


The nodeValue property can be used to change or clear the value of a text
node:ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="";

<html>

29
<head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
document.write("Value: " + x.nodeValue);
document.write("<br />");
x.nodeValue="";
document.write("Value: " + x.nodeValue);
</script></body></html>

Result:
Value: Everyday Italian
Value:

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Set the variable x to be the text node of the first title element
3. Use the nodeValue property to clear the text from the text node

Loop through and change the text node of all <title> elements:

*Remove an Attribute Node by Name


The removeAttribute(name) method is used to remove an attribute node by its name.

Example: removeAttribute('category')
The following code fragment removes the "category" attribute in the first <book>
element:ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book");
x[0].removeAttribute("category");

<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book');
document.write(x[0].getAttribute('category'));
document.write("<br />");
x[0].removeAttribute('category');
document.write(x[0].getAttribute('category'));
</script></body></html>

Result:
cooking
null

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Use getElementsByTagName() to get book nodes
3. Remove the "category" attribute form the first book element node

Loop through and remove the "category" attribute of all <book> elements:

*Remove Attribute Nodes by Object


The removeAttributeNode(node) method is used to remove an attribute node, using the node object as
parameter.

Example: removeAttributeNode(x)
The following code fragment removes all the attributes of all <book>
elements:ExamplexmlDoc=loadXMLDoc("books.xml");

30
x=xmlDoc.getElementsByTagName("book");
for (i=0;i<x.length;i++)
{
while (x[i].attributes.length>0)
{
attnode=x[i].attributes[0];
old_att=x[i].removeAttributeNode(attnode);
}
}

code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book');
for (i=0;i<x.length;i++)
{
while (x[i].attributes.length>0)
{
attnode=x[i].attributes[0];
old_att=x[i].removeAttributeNode(attnode);
document.write("Removed: " + old_att.nodeName)
document.write(": " + old_att.nodeValue)
document.write("<br />")
}
}
</script></body></html>

Result:
Removed: category: cooking
Removed: category: children
Removed: category: web
Removed: category: web
Removed: cover: paperback

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Use getElementsByTagName() to get all book nodes
3. For each book element check if there are any attributes. While there are attributes in a book
element, remove the attribute

XML DOM Replace Nodes


The replaceChild() method replaces a specified node.
The nodeValue property replaces text in a text node.

*Replace an Element Node


The replaceChild() method is used to replace a node.
The following code fragment replaces the first <book> element:ExamplexmlDoc=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");
//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

31
x.replaceChild(newNode,y);

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
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");
//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);
z=xmlDoc.getElementsByTagName("title");
for (i=0;i<z.length;i++)
{
document.write(z[i].childNodes[0].nodeValue);
document.write("<br />");
}
</script></body></html>

Result:
A Notebook
Harry Potter
XQuery Kick Start
Learning XML

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Create a new element node <book>
3. Create a new element node <title>
4. Create a new text node with the text "A Notebook"
5. Append the new text node to the new element node <title>
6. Append the new element node <title> to the new element node <book>
7. Replace the first <book> element node with the new <book> element node

*Replace Data In a Text Node


The replaceData() method is used to replace data in a text node.
The replaceData() method has three parameters:
1. offset - Where to begin replacing characters. Offset value starts at zero
2. length - How many characters to replace
3. string - The string to insertExamplexmlDoc=loadXMLDoc("books.xml");

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

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
document.write(x.nodeValue);

32
x.replaceData(0,8,"Easy");
document.write("<br />");
document.write(x.nodeValue);
</script></body></html>

Result:
Everyday Italian
Easy Italian

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Get the text node of the first <title> element node
3. Use the replaceDat method to replace the eight first characters from the text node with "Easy"
*
Use the nodeValue Property Instead
It is easier to replace the data in a text node using the nodeValue property.
The following code fragment will replace the text node value in the first <title> element with "Easy
Italian":ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Italian";

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
document.write(x.nodeValue);
x.nodeValue="Easy Italian";
document.write("<br />");
document.write(x.nodeValue);
</script></body></html>

Result:
Everyday Italian
Easy Italian

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Get the text node of the first <title> element node
3. Use the nodeValue property to change the text of the text node

XML DOM Create Nodes


Create a CDATA section node

*Create a New Element Node


The createElement() method creates a new element node:ExamplexmlDoc=loadXMLDoc("books.xml");
newel=xmlDoc.createElement("edition");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js"> </script>
</head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
newel=xmlDoc.createElement("edition");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);

33
document.write(x.getElementsByTagName("edition")[0].nodeName);
</script></body></html>

Result:
edition

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Create a new element node <edition>
3. Append the element node to the first <book> element

*Create a New Attribute Node


The createAttribute() is used to create a new attribute node:ExamplexmlDoc=loadXMLDoc("books.xml");
newatt=xmlDoc.createAttribute("edition");
newatt.nodeValue="first";
x=xmlDoc.getElementsByTagName("title");
x[0].setAttributeNode(newatt);

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
newatt=xmlDoc.createAttribute("edition");
newatt.nodeValue="first";
x=xmlDoc.getElementsByTagName("title");
x[0].setAttributeNode(newatt);
document.write("Edition: ");
document.write(x[0].getAttribute("edition"));
</script></body></html>

Result:
Edition: first

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Create a new attribute node "edition"
3. Set the value of the attribute node to "first"
4. Add the new attribute node to the first <title> element
Note: If the attribute already exists, it is replaced by the new one.

*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.ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("edition","first");

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title");
x[0].setAttribute("edition","first");
document.write("Edition: ");
document.write(x[0].getAttribute("edition"));
</script></body>
</html>

34
Result:
Edition: first

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Set (create) the attribute "edition" with the value "first" for the first <book> element

*Create a Text Node


The createTextNode() method creates a new text node:ExamplexmlDoc=loadXMLDoc("books.xml");
newel=xmlDoc.createElement("edition");
newtext=xmlDoc.createTextNode("first");
newel.appendChild(newtext);
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
newel=xmlDoc.createElement("edition");
newtext=xmlDoc.createTextNode("first");
newel.appendChild(newtext);
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);
//Output title and edition
document.write(x.getElementsByTagName("title")[0].childNodes[0].nodeValue);
document.write(" - Edition: ");
document.write(x.getElementsByTagName("edition")[0].childNodes[0].nodeValue);
</script></body></html>

Result:
Everyday Italian - Edition: first

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Create a new element node <edition>
3. Create a new text node with the text "first"
4. Append the new text node to the element node
5. Append the new element node to the first <book> element

*Create a CDATA Section Node


The createCDATASection() method creates a new CDATA section
node.ExamplexmlDoc=loadXMLDoc("books.xml");
newCDATA=xmlDoc.createCDATASection("Special Offer & Book Sale");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newCDATA);

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
newCDATA=xmlDoc.createCDATASection("Special Offer & Book Sale");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newCDATA);
document.write(x.lastChild.nodeValue);
</script></body></html>

35
Result:
Special Offer & Book Sale

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Create a new CDATA section node
3. Append the new CDATA node to the first <book> element

*Create a Comment Node


The createComment() method creates a new comment node.ExamplexmlDoc=loadXMLDoc("books.xml");
newComment=xmlDoc.createComment("Revised March 2008");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newComment);

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
newComment=xmlDoc.createComment("Revised April 2008");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newComment);
document.write(x.lastChild.nodeValue);
</script></body></html>

Result:
Revised April 2008

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Create a new comment node
3. Append the new comment node to the first <book> element

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.

The following code fragment creates an element (<edition>), and adds it after the last child of the first
<book> element:ExamplexmlDoc=loadXMLDoc("books.xml");
newel=xmlDoc.createElement("edition");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script>
</head>
<body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
newel=xmlDoc.createElement("edition");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);
document.write(x.getElementsByTagName("edition")[0].nodeName);
</script></body>
</html>

36
Result:
edition

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Create a new node <edition>
3. Append the node to the first <book> element

*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:ExamplexmlDoc=loadXMLDoc("books.xml");
newNode=xmlDoc.createElement("book");
x=xmlDoc.documentElement;
y=xmlDoc.getElementsByTagName("book")[3];
x.insertBefore(newNode,y);

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
newNode=xmlDoc.createElement("book");
x=xmlDoc.documentElement;
y=xmlDoc.getElementsByTagName("book");
document.write("Book elements before: " + y.length);
document.write("<br />");
x.insertBefore(newNode,y[3]);
y=xmlDoc.getElementsByTagName("book");
document.write("Book elements after: " + y.length);
</script></body></html>

Result:
Book elements before: 4
Book elements after: 5

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Create a new element node <book>
3. Insert the new node in front of the last <book> element node
If the second parameter of insertBefore() is null, the new node will be added after the last existing child
node.
x.insertBefore(newNode,null) and x.appendChild(newNode) will both append a new child node to x.

*Add a New Attribute


There is no method called addAtribute().
The setAttribute() method creates a new attribute if the attribute does not
exist:ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("edition","first");

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title");
x[0].setAttribute("edition","first");
document.write("Edition: ");

37
document.write(x[0].getAttribute("edition"));
</script></body></html>

Result:
Edition: first

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Set (create) the attribute "edition" with the value "first" for the first <book> element
Note: If the attribute already exists, the setAttribute() method will overwrite the existing value.

Add Text to a Text Node - insertData()


The insertData() method inserts data into an existing text node.

The insertData() method has two parameters:


 offset - Where to begin inserting characters (starts at zero)
 string - The string to insert

*The following code fragment will add "Easy" to the text node of the first <title> element of the loaded
XML:ExamplexmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.insertData(0,"Easy ");

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
document.write(x.nodeValue);
x.insertData(0,"Easy ");
document.write("<br />");
document.write(x.nodeValue);
</script></body></html>

Result:
Everyday Italian
Easy Everyday Italian

XML DOM Clone Nodes


Copy a Node
 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:ExamplexmlDoc=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 />");
}

Code:
<html>

38
<head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book')[0];
cloneNode=x.cloneNode(true);
xmlDoc.documentElement.appendChild(cloneNode);
//Output all titles
y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++)
{
document.write(y[i].childNodes[0].nodeValue);
document.write("<br />");
}
</script></body></html>

Output:
Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML
Everyday Italian

Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Get the node to copy
3. Copy the node into "newNode" using the cloneNode method
4. Append the new node to the the root node of the XML document
5. Output all titles for all books in the document

The XMLHttpRequest Object


The XMLHttpRequest object provides a way to communicate with a server after a web page has loaded.

What is the XMLHttpRequest Object?


 The XMLHttpRequest object is the developers dream, because you can:
 Update a web page with new data 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
 The XMLHttpRequest object is supported in all modern browsers.

Creating an XMLHttpRequest Object


Creating an XMLHttpRequest object is done with one single line of JavaScript.
In all modern browsers (including IE7):xmlhttp=new XMLHttpRequest()
In Internet Explorer 5 and 6:xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")

Example
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for all new browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5 and IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

39
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}

function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = OK
// ...our code here...
}
else
{
alert("Problem retrieving XML data");
}
}
}
</script>

Note: onreadystatechange is an event handler. The value (state_Change) is the name of a function which is
triggered when the state of the XMLHttpRequest object changes. States run from 0 (uninitialized) to 4
(complete). Only when the state = 4, we can execute our code.

Why Use Async=true?


Our examples use "true" in the third parameter of open().
This parameter specifies whether the request should be handled asynchronously.
True means that the script continues to run after the send() method, without waiting for a response from the
server.
The onreadystatechange event complicates the code. But it is the safest way if you want to prevent the code
from stopping if you don't get a response from the server.
By setting the parameter to "false", your can avoid the extra onreadystatechange code. Use this if it's not
important to execute the rest of the code if the request fails.

 Load a textfile into a div element with XML HTTP

Code:
<html><head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for Firefox, Opera, IE7, etc.
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)

40
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = "OK"
document.getElementById('T1').innerHTML=xmlhttp.responseText;
}
else
{
alert("Problem retrieving data:" + xmlhttp.statusText);
}
}
}
</script></head>
<body onload="loadXMLDoc('test_xmlhttp.txt')">
<div id="T1" style="border:1px solid black;height:40;width:300;padding:5"></div><br />
<button onclick="loadXMLDoc('test_xmlhttp2.txt')">Click</button>
</body></html>

 Make a HEAD request with XML HTTP

Code:
<html><head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for Firefox, Mozilla, IE7, etc.
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"

41
if (xmlhttp.status==200)
{// 200 = "OK"
document.getElementById('p1').innerHTML=xmlhttp.getAllResponseHeaders();
}
else
{
alert("Problem retrieving data:" + xmlhttp.statusText);
}
}
}
</script></head><body>
<p id="p1">
The getAllResponseHeaders() function returns the headers of a resource.
The headers contain file information like length,
server-type, content-type, date-modified, etc.</p>
<button onclick="loadXMLDoc('test_xmlhttp.txt')">Get Headers</button>
</body></html>

 Make a specified HEAD request with XML HTTP


Code:
<html><head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// all modern browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// for IE5, IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = "OK"
document.getElementById('p1').innerHTML="This file was last modified on: " +
xmlhttp.getResponseHeader('Last-Modified');
}
else
{
alert("Problem retrieving data:" + xmlhttp.statusText);
}
}
}
</script>
</head><body>

42
<p id="p1">
The getResponseHeader() function returns a header from a resource.
Headers contain file information like length,
server-type, content-type, date-modified, etc.</p>
<button onclick="loadXMLDoc('test_xmlhttp.txt')">Get "Last-Modified"</button>
</body></html>

 List data from an XML file with XML HTTP

CodE:
<html><head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for IE7, Firefox, Mozilla, etc.
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5, IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=onResponse;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function onResponse()
{
if(xmlhttp.readyState!=4) return;
if(xmlhttp.status!=200)
{
alert("Problem retrieving XML data");
return;
}
txt="<table border='1'>";
x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
for (i=0;i<x.length;i++)
{
txt=txt + "<tr>";
xx=x[i].getElementsByTagName("TITLE");
{
try
{
txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er)
{
txt=txt + "<td> </td>";
}
}
xx=x[i].getElementsByTagName("ARTIST");
{
try

43
{
txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er)
{
txt=txt + "<td> </td>";
}
}
txt=txt + "</tr>";
}
txt=txt + "</table>";
document.getElementById('copy').innerHTML=txt;
}
</script></head>
<body><div id="copy">
<button onclick="loadXMLDoc('cd_catalog.xml')">Get CD info</button>
</div></body></html>

XML / ASP
You can also open and send an XML document to an ASP page on the server, analyze the request, and
send back the result.
Example
<html>
<body>
<script type="text/javascript">
xmlHttp=null;
if (window.XMLHttpRequest)
{// code for IE7, Firefox, Opera, etc.
xmlHttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp!=null)
{
xmlHttp.open("GET", "note.xml", false);
xmlHttp.send(null);
xmlDoc=xmlHttp.responseText;

xmlHttp.open("POST", "demo_dom_http.asp", false);


xmlHttp.send(xmlDoc);
document.write(xmlHttp.responseText);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
</script></body></html>

Result:
The TO element contains: Tove

The ASP page, written in VBScript:


<%
set xmldoc = Server.CreateObject("Microsoft.XMLDOM")
xmldoc.async=false
xmldoc.load(request)
for each x in xmldoc.documentElement.childNodes
if x.NodeName = "to" then name=x.text
next
response.write(name)

44
%>

You send the result back to the client using the response.write property.

Is the XMLHttpRequest Object a W3C Standard?


The XMLHttpRequest object is not specified in any W3C recommendation.
However, the W3C DOM Level 3 "Load and Save" specification contains some similar functionality, but
these are not implemented in any browsers yet.

XML DOM Node Types


The DOM presents a document as a hierarchy of node objects.

Examples
The examples below use the XML file books.xml.
A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

 Display nodeName and nodeType of all elements

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
document.write("Nodename: " + xmlDoc.nodeName);
document.write(" (nodetype: " + xmlDoc.nodeType + ")<br />");
x=xmlDoc.documentElement;
document.write("Nodename: " + x.nodeName);
document.write(" (nodetype: " + x.nodeType + ")<br />");
y=x.childNodes;
for (i=0;i<y.length;i++)
{
document.write("Nodename: " + y[i].nodeName);
document.write(" (nodetype: " + y[i].nodeType + ")<br />");
for (z=0;z<y[i].childNodes.length;z++)
{
document.write("Nodename: " + y[i].childNodes[z].nodeName);
document.write(" (nodetype: " + y[i].childNodes[z].nodeType + ")<br />");
}
}
</script></body></html>

Result:
Nodename: #document (nodetype: 9)
Nodename: bookstore (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: book (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: title (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: author (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: year (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: price (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: #text (nodetype: 3)
Nodename: book (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: title (nodetype: 1)
Nodename: #text (nodetype: 3)

45
Nodename: author (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: year (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: price (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: #text (nodetype: 3)
Nodename: book (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: title (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: author (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: author (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: author (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: author (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: author (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: year (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: price (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: #text (nodetype: 3)
Nodename: book (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: title (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: author (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: year (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: price (nodetype: 1)
Nodename: #text (nodetype: 3)
Nodename: #text (nodetype: 3)

 Display nodeName and nodeValue of all elements

Code:
<html><head>
<script type="text/javascript" src="loadxmldoc.js">
</script></head><body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
document.write("Nodename: " + xmlDoc.nodeName);
document.write(" (value: " + xmlDoc.childNodes[0].nodeValue + ")<br />");
x=xmlDoc.documentElement;
document.write("Nodename: " + x.nodeName);
document.write(" (value: " + x.childNodes[0].nodeValue + ")<br />");
y=xmlDoc.documentElement.childNodes;
for (i=0;i<y.length;i++)
{
if (y[i].nodeType!=3)
{
document.write("Nodename: " + y[i].nodeName);
document.write(" (value: " + y[i].childNodes[0].nodeValue + ")<br />");
for (z=0;z<y[i].childNodes.length;z++)
{
if (y[i].childNodes[z].nodeType!=3)
{

46
document.write("Nodename: " + y[i].childNodes[z].nodeName);
document.write(" (value: " + y[i].childNodes[z].childNodes[0].nodeValue + ")<br />");
}
}
}
}
</script></body></html>

Result:
Nodename: #document (value: Edited by XMLSpy® )
Nodename: bookstore (value: )
Nodename: book (value: )
Nodename: title (value: Everyday Italian)
Nodename: author (value: Giada De Laurentiis)
Nodename: year (value: 2005)
Nodename: price (value: 30.00)
Nodename: book (value: )
Nodename: title (value: Harry Potter)
Nodename: author (value: J K. Rowling)
Nodename: year (value: 2005)
Nodename: price (value: 29.99)
Nodename: book (value: )
Nodename: title (value: XQuery Kick Start)
Nodename: author (value: James McGovern)
Nodename: author (value: Per Bothner)
Nodename: author (value: Kurt Cagle)
Nodename: author (value: James Linn)
Nodename: author (value: Vaidyanathan Nagarajan)
Nodename: year (value: 2003)
Nodename: price (value: 49.99)
Nodename: book (value: )
Nodename: title (value: Learning XML)
Nodename: author (value: Erik T. Ray)
Nodename: year (value: 2003)
Nodename: price (value: 39.95)

Node Types
The following table lists the different W3C node types, and which node types they may have as children:
Node type Description Children
Document Represents the entire document (the root-node Element (max. one),
of the DOM tree) ProcessingInstruction, Comment,
DocumentType
DocumentFragment Represents a "lightweight" Document object, Element, ProcessingInstruction,
which can hold a portion of a document Comment, Text, CDATASection,
EntityReference
DocumentType Provides an interface to the entities defined for None
the document
ProcessingInstruction Represents a processing instruction None

EntityReference Represents an entity reference Element, ProcessingInstruction,


Comment, Text, CDATASection,
EntityReference
Element Represents an element Element, Text, Comment,
ProcessingInstruction,
CDATASection, EntityReference
Attr Represents an attribute Text, EntityReference

Text Represents textual content in an element or None


attribute

47
CDATASection Represents a CDATA section in a document None
(text that will NOT be parsed by a parser)
Comment Represents a comment None

Entity Represents an entity Element, ProcessingInstruction,


Comment, Text, CDATASection,
EntityReference
Notation Represents a notation declared in the DTD None

Node Types - Return Values


The following table lists what the nodeName and the nodeValue properties will return for each node type:
Node type Description Children
Document #document null

DocumentFragment #document fragment null

DocumentType doctype name null

EntityReference entity reference name null

Element element name null

Attr attribute name attribute value

ProcessingInstruction target content of node

Comment #comment comment text

Text #text content of node

CDATASection #cdata-section content of node

Entity entity name null

Notation notation name null

NodeTypes - Named Constants


NodeType Named Constant
1 ELEMENT_NODE
2 ATTRIBUTE_NODE
3 TEXT_NODE
4 CDATA_SECTION_NODE
5 ENTITY_REFERENCE_NODE
6 ENTITY_NODE
7 PROCESSING_INSTRUCTION_NODE
8 COMMENT_NODE
9 DOCUMENT_NODE
10 DOCUMENT_TYPE_NODE
11 DOCUMENT_FRAGMENT_NODE
12 NOTATION_NODE

XML DOM - The Node Object


The Node object represents a node in the document tree.

The Node Object


The Node object is the primary data type for the entire DOM.

48
The Node object represents a single node in the document tree.
A node can be an element node, an attribute node, a text node, or any other of the node types explained in
the "Node types" chapter.
Notice that while all objects inherits the Node properties / methods for dealing with parents and children, not
all objects can have parents or children. For example, Text nodes may not have children, and adding
children to such nodes results in a DOM error.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard)

Node Object Properties


Property Description IE F O W3C

baseURI Returns the absolute base URI of a node No 1 No Yes

childNodes Returns a NodeList of child nodes for a node 5 1 9 Yes

firstChild Returns the first child of a node 5 1 9 Yes

lastChild Returns the last child of a node 5 1 9 Yes

localName Returns the local part of the name of a node No 1 9 Yes

namespaceURI Returns the namespace URI of a node No 1 9 Yes

nextSibling Returns the node immediately following a node 5 1 9 Yes

nodeName Returns the name of a node, depending on its type 5 1 9 Yes

nodeType Returns the type of a node 5 1 9 Yes

nodeValue Sets or returns the value of a node, depending on 5 1 9 Yes


its type
ownerDocument Returns the root element (document object) for a 5 1 9 Yes
node
parentNode Returns the parent node of a node 5 1 9 Yes

prefix Sets or returns the namespace prefix of a node No 1 9 Yes

previousSibling Returns the node immediately before a node 5 1 9 Yes

textContent Sets or returns the textual content of a node and its No 1 No Yes
descendants
text Returns the text of a node and its descendants. IE- 5 No No No
only property
xml Returns the XML of a node and its descendants. 5 No No No
IE-only property

Node Object Methods

Method Description IE F O W3C

appendChild() Adds a new child node to the end of the list of 5 1 9 Yes
children of a node
cloneNode() Clones a node 5 1 9 Yes

compareDocumentPosition() Compares the document position of two nodes No 1 No Yes

getFeature(feature,version) Returns a DOM object which implements the No Yes


specialized APIs of the specified feature and
version
getUserData(key) Returns the object associated to a key on a this No Yes
node. The object must first have been set to this
node by calling setUserData with the same key
hasAttributes() Returns true if a node has any attributes, No 1 9 Yes
otherwise it returns false

49
hasChildNodes() Returns true if a node has any child nodes, 5 1 9 Yes
otherwise it returns false
insertBefore() Inserts a new child node before an existing child 5 1 9 Yes
node
isDefaultNamespace(URI) Returns whether the specified namespaceURI is No Yes
the default
isEqualNode() Checks if two nodes are equal No No No Yes

isSameNode() Checks if two nodes are the same node No 1 No Yes

isSupported(feature,version) Returns whether a specified feature is supported 9 Yes


on a node
lookupNamespaceURI() Returns the namespace URI matching a specified No 1 No Yes
prefix
lookupPrefix() Returns the prefix matching a specified No 1 No Yes
namespace URI
normalize() Puts all text nodes underneath a node (including 5 1 9 Yes
attributes) into a "normal" form where only
structure (e.g., elements, comments, processing
instructions, CDATA sections, and entity
references) separates Text nodes, i.e., there are
neither adjacent Text nodes nor empty Text
nodes
removeChild() Removes a child node 5 1 9 Yes

replaceChild() Replaces a child node 5 1 9 Yes

setUserData(key,data,handler) Associates an object to a key on a node No Yes

XML DOM - The NodeList Object


The NodeList object represents an ordered list of nodes.

The NodeList object


The nodes in the NodeList can be accessed through their index number (starting from 0).
The NodeList keeps itself up-to-date. If an element is deleted or added, in the node list or the XML
document, the list is automatically updated.
Note: In a node list, the nodes are returned in the order in which they are specified in the XML.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard)

NodeList Object Properties


Property Description IE F O W3C

length Returns the number of nodes in a node list 5 1 9 Yes

NodeList Object Methods


Method Description IE F O W3C

item() Returns the node at the specified index in a node 5 1 9 Yes


list

XML DOM - The NamedNodeMap Object


The NamedNodeMap object represents an unordered list of nodes.

The NamedNodeMap object


The nodes in the NamedNodeMap can be accessed through their name.
The NamedNodeMap keeps itself up-to-date. If an element is deleted or added, in the node list or the XML
document, the list is automatically updated.
Note: In a named node map, the nodes are not returned in any particular order.

50
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard)

NamedNodeMap Object Properties


Property Description IE F O W3C

length Returns the number of nodes in a node list 5 1 9 Yes

NamedNodeMap Object Methods


Method Description IE F O W3C

getNamedItem() Returns the specified node (by name) 5 1 9 Yes

getNamedItemNS() Returns the specified node (by name and 9 Yes


namespace)
item() Returns the node at the specified index 5 1 9 Yes

removeNamedItem() Removes the specified node (by name) 6 1 9 Yes

removeNamedItemNS() Removes the specified node (by name and 9 Yes


namespace)
setNamedItem() Sets the specified node (by name) 9 Yes

setNamedItemNS() Sets the specified node (by name and 9 Yes


namespace)

XML DOM - The Document Object


The Document object represents the entire XML document.

The Document object


The Document object is the root of a document tree, and gives us the primary access to the document's
data.
Since element nodes, text nodes, comments, processing instructions, etc. cannot exist outside the
document, the Document object also contains methods to create these objects. The Node objects have a
ownerDocument property which associates them with the Document where they were created.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard)

Document Object Properties


Property Description IE F O W3C

async Specifies whether downloading of an XML file 5 1.5 9 No


should be handled asynchronously or not

childNodes Returns a NodeList of child nodes for the 5 1 9 Yes


document

doctype Returns the Document Type Declaration 6 1 9 Yes


associated with the document

documentElement Returns the root node of the document 5 1 9 Yes

documentURI Sets or returns the location of the document No 1 9 Yes

domConfig Returns the configuration used when No Yes


normalizeDocument() is invoked

51
firstChild Returns the first child node of the document 5 1 9 Yes

implementation Returns the DOMImplementation object that No 1 9 Yes


handles this document

inputEncoding Returns the encoding used for the document No 1 No Yes


(when parsing)

lastChild Returns the last child node of the document 5 1 9 Yes

nodeName Returns the name of a node (depending on its 5 1 9 Yes


type)

nodeType Returns the node type of a node 5 1 9 Yes

nodeValue Sets or returns the value of a node (depending 5 1 9 Yes


on its type)

strictErrorChecking Sets or returns whether error-checking is No 1 No Yes


enforced or not

text Returns the text of a node and its descendants. 5 No No No


IE-only property

xml Returns the XML of a node and its descendants. 5 No No No


IE-only property

xmlEncoding Returns the XML encoding of the document No 1 No Yes

xmlStandalone Sets or returns whether the document is No 1 No Yes


standalone

xmlVersion Sets or returns the XML version of the No 1 No Yes


document

Document Object Methods


Method Description IE F O W3C

adoptNode(sourcenode) Adopts a node from another document to this No Yes


document, and returns the adopted node

createAttribute(name) Creates an attribute node with the specified 6 1 9 Yes


name, and returns the new Attr object

createAttributeNS(uri,name) Creates an attribute node with the specified 9 Yes

52
name and namespace, and returns the new Attr
object

createCDATASection() Creates a CDATA section node 5 1 9 Yes

createComment() Creates a comment node 6 1 9 Yes

createDocumentFragment() Creates an empty DocumentFragment object, 5 1 9 Yes


and returns it

createElement() Creates an element node 5 1 9 Yes

createElementNS() Creates an element node with a specified No 1 9 Yes


namespace

createEntityReference(name) Creates an EntityReference object, and returns 5 No Yes


it

createProcessingInstruction(target,d Creates a ProcessingInstruction object, and 5 9 Yes


ata) returns it

createTextNode() Creates a text node 5 1 9 Yes

createElementNS() Creates an element node with a specified No 1 9 Yes


namespace

createEntityReference(name) Creates an EntityReference object, and returns 5 No Yes


it

createProcessingInstruction(target,d Creates a ProcessingInstruction object, and 5 9 Yes


ata) returns it

createTextNode() Creates a text node 5 1 9 Yes

getElementById(id) Returns the element that has an ID attribute 5 1 9 Yes


with the given value. If no such element
exists, it returns null
getElementsByTagName() Returns a NodeList of all elements with a 5 1 9 Yes
specified name
getElementsByTagNameNS() Returns a NodeList of all elements with a No 1 9 Yes
specified name and namespace
importNode(nodetoimport,deep) Imports a node from another document to 9 Yes
this document. This method creates a new
copy of the source node. If the deep
parameter is set to true, it imports all children
of the specified node. If set to false, it imports
only the node itself. This method returns the
imported node

53
normalizeDocument() No Yes

renameNode() Renames an element or attribute node No Yes

XML DOM - The DocumentImplementation Object


The DOMImplementation object performs operations that are independent of any particular instance of the
document object model.

The DocumentImplementation object


The DOMImplementation object performs operations that are independent of any particular instance of the
document object model.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard)

DocumentImplementation Object Methods


Method Description IE F O W3C

createDocument(nsURI, name, Creates a new DOM Document object of the Yes


doctype) specified doctype
createDocumentType(name, pubId, Creates an empty DocumentType node Yes
systemId)
getFeature(feature, version) Returns an object which implements the APIs of Yes
the specified feature and version, if the is any

hasFeature(feature, version) Checks whether the DOM implementation Yes


implements a specific feature and version

XML DOM - The DocumentType Object


The DocumentType object provides an interface to the entities defined for an XML document.

The DocumentType object


Each document has a DOCTYPE attribute that whose value is either null or a DocumentType object.

The DocumentType object provides an interface to the entities defined for an XML document.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard)

DocumentType Object Properties


Property Description IE F O W3C

entities Returns a NamedNodeMap containing the 6 No 9 Yes


entities declared in the DTD
internalSubset Returns the internal DTD as a string No No No Yes

name Returns the name of the DTD 6 1 9 Yes

notations Returns a NamedNodeMap containing the 6 No 9 Yes


notations declared in the DTD
systemId Returns the system identifier of the external No 1 9 Yes
DTD

XML DOM - The ProcessingInstruction Object


The ProcessingInstruction object represents a processing instruction.

54
The ProcessingInstruction object
The ProcessingInstruction object represents a processing instruction.
A processing instruction is used as a way to keep processor-specific information in the text of the XML
document.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard)

ProcessingInstruction Object Properties


Property Description IE F O W3C

data Sets or returns the content of this No Yes


processing instruction
target Returns the target of this processing No Yes
instruction

XML DOM - The Element Object


The Element object represents an element in an XML document.

The Element object


The Element object represents an element in an XML document. Elements may contain attributes, other
elements, or text. If an element contains text, the text is represented in a text-node.
IMPORTANT! Text is always stored in text nodes. A common error in DOM processing is to navigate to an
element node and expect it to contain the text. However, even the simplest element node has a text node
under it. For example, in <year>2005</year>, there is an element node (year), and a text node under it,
which contains the text (2005).
Because the Element object is also a Node, it inherits the Node object's properties and methods.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard)

Element Object Properties


Property Description IE F O W3C

attributes Returns a NamedNodeMap of attributes for the 5 1 9 Yes


element
baseURI Returns the absolute base URI of the element No 1 No Yes

childNodes Returns a NodeList of child nodes for the 5 1 9 Yes


element
firstChild Returns the first child of the element 5 1 9 Yes

lastChild Returns the last child of the element 5 1 9 Yes

localName Returns the local part of the name of the No 1 9 Yes


element
namespaceURI Returns the namespace URI of the element No 1 9 Yes

nextSibling Returns the node immediately following the 5 1 9 Yes


element
nodeName Returns the name of the node, depending on 5 1 9 Yes
its type
nodeType Returns the type of the node 5 1 9 Yes

ownerDocument Returns the root element (document object) for 5 1 9 Yes


an element
parentNode Returns the parent node of the element 5 1 9 Yes

prefix Sets or returns the namespace prefix of the No 1 9 Yes


element

55
previousSibling Returns the node immediately before the 5 1 9 Yes
element
schemaTypeInfo Returns the type information associated with No Yes
the element
tagName Returns the name of the element 5 1 9 Yes

textContent Sets or returns the text content of the element No 1 No Yes


and its descendants
text Returns the text of the node and its 5 No No No
descendants. IE-only property
xml Returns the XML of the node and its 5 No No No
descendants. IE-only property

Element Object Methods


Method Description IE F O W3C

appendChild() Adds a new child node to the end of the 5 1 9 Yes


list of children of the node
cloneNode() Clones a node 5 1 9 Yes

compareDocumentPosition() Compares the document position of two No 1 No Yes


nodes
getAttribute() Returns the value of an attribute 5 1 9 Yes

getAttributeNS() Returns the value of an attribute (with a No 1 9 Yes


namespace)
getAttributeNode() Returns an attribute node as an 5 1 9 Yes
Attribute object
getAttributeNodeNS() Returns an attribute node (with a No 9 Yes
namespace) as an Attribute object
getElementsByTagName() Returns a NodeList of matching 5 1 9 Yes
element nodes, and their children
getElementsByTagNameNS() Returns a NodeList of matching No 1 9 Yes
element nodes (with a namespace),
and their children
getUserData(key) Returns the object associated to a key No Yes
on a this node. The object must first
have been set to this node by calling
setUserData with the same key
hasAttribute() Returns whether an element has any 5 1 9 Yes
attributes matching a specified name
hasAttributeNS() Returns whether an element has any No 1 9 Yes
attributes matching a specified name
and namespace
hasAttributes() Returns whether the element has any 5 1 9 Yes
attributes
hasChildNodes() Returns whether the element has any 5 1 9 Yes
child nodes
insertBefore() Inserts a new child node before an 5 1 9 Yes
existing child node
isDefaultNamespace(URI) Returns whether the specified No Yes
namespaceURI is the default
isEqualNode() Checks if two nodes are equal No No No Yes

isSameNode() Checks if two nodes are the same node No 1 No Yes

isSupported(feature,version) Returns whether a specified feature is 9 Yes


supported on the element
lookupNamespaceURI() Returns the namespace URI matching No 1 No Yes
a specified prefix

56
lookupPrefix() Returns the prefix matching a specified No 1 No Yes
namespace URI
normalize() Puts all text nodes underneath this 5 1 9 Yes
element (including attributes) into a
"normal" form where only structure
(e.g., elements, comments, processing
instructions, CDATA sections, and
entity references) separates Text
nodes, i.e., there are neither adjacent
Text nodes nor empty Text nodes
removeAttribute() Removes a specified attribute 5 1 9 Yes

removeAttributeNS() Removes a specified attribute (with a No 1 9 Yes


namespace)
removeAttributeNode() Removes a specified attribute node 5 1 9 Yes

removeChild() Removes a child node 5 1 9 Yes

replaceChild() Replaces a child node 5 1 9 Yes

setUserData(key,data,handler) Associates an object to a key on the No Yes


element
setAttribute() Adds a new attribute 5 1 9 Yes

setAttributeNS() Adds a new attribute (with a 1 9 Yes


namespace)
setAttributeNode() Adds a new attribute node 5 1 9 Yes

setAttributeNodeNS(attrnode) Adds a new attribute node (with a 9 Yes


namespace)
setIdAttribute(name,isId) If the isId property of the Attribute object No Yes
is true, this method declares the
specified attribute to be a user-
determined ID attribute
setIdAttributeNS(uri,name,isId) If the isId property of the Attribute object No Yes
is true, this method declares the
specified attribute (with a namespace)
to be a user-determined ID attribute
setIdAttributeNode(idAttr,isId) If the isId property of the Attribute object No Yes
is true, this method declares the
specified attribute to be a user-
determined ID attribute
XML DOM - The Attr Object
The Attr object represents an attribute of an Element object.

The Attr object


The Attr object represents an attribute of an Element object. The allowable values for attributes are usually
defined in a DTD.
Because the Attr object is also a Node, it inherits the Node object's properties and methods. However, an
attribute does not have a parent node and is not considered to be a child node of an element, and will return
null for many of the Node properties.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard)

Attr Object Properties


Method Description IE F O W3C

baseURI Returns the absolute base URI of the No 1 No Yes


attribute
isId Returns true if the attribute is known to No No No Yes
be of type ID, otherwise it returns false

57
localName Returns the local part of the name of No 1 9 Yes
the attribute
name Returns the name of the attribute 5 1 9 Yes

namespaceURI Returns the namespace URI of the No 1 9 Yes


attribute
nodeName Returns the name of the node, 5 1 9 Yes
depending on its type
nodeType Returns the type of the node 5 1 9 Yes

nodeValue Sets or returns the value of the node, 5 1 9 Yes


depending on its type
ownerDocument Returns the root element (document 5 1 9 Yes
object) for an attribute
ownerElement Returns the element node the attribute No 1 9 Yes
is attached to
prefix Sets or returns the namespace prefix of No 1 9 Yes
the attribute
schemaTypeInfo Returns the type information associated No No No Yes
with this attribute
specified Returns true if the attribute value is set 5 1 9 Yes
in the document, and false if it's a
default value in a DTD/Schema.
textContent Sets or returns the textual content of an No 1 9 Yes
attribute
text Returns the text of the attribute. IE-only 5 No No No
property
value Sets or returns the value of the attribute 5 1 9 Yes

xml Returns the XML of the attribute. IE- 5 No No No


only property

XML DOM - The Text Object


The Text object represents the textual content of an element or attribute.

The Text object


The Text object represents the textual content of an element or attribute.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard)

Text Object Properties


Method Description IE F O W3C

data Sets or returns the text of the element 6 1 9 Yes


or attribute
isElementContentWhitespace Returns true if the text node contains No No No Yes
content whitespace, otherwise it returns
false
length Returns the length of the text of the 6 1 9 Yes
element or attribute
wholeText Returns all text of text nodes adjacent No No No Yes
to this node, concatenated in document
order

Text Object Methods


Method Description IE F O W3C

58
appendData() Appends data to the node 6 1 9 Yes

deleteData() Deletes data from the node 6 1 9 Yes

insertData() Inserts data into the node 6 1 9 Yes

replaceData() Replaces data in the node 6 1 9 Yes

replaceWholeText(text) Replaces the text of this node and all No No No Yes


adjacent text nodes with the specified
text
splitText() Splits this node into two nodes at the 6 1 9 Yes
specified offset, and returns the new
node that contains the text after the
offset
substringData() Extracts data from the node 6 1 9 Yes

XML DOM - The CDATASection Object


The CDATASection object represents a CDATA section in a document.

The CDATASection object


The CDATASection object represents a CDATA section in a document.
A CDATA section contains text that will NOT be parsed by a parser. Tags inside a CDATA section will NOT
be treated as markup and entities will not be expanded. The primary purpose is for including material such
as XML fragments, without needing to escape all the delimiters.
The only delimiter that is recognized in a CDATA section is "]]>" - which indicates the end of the CDATA
section. CDATA sections cannot be nested.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard)

CDATASection Object Properties


Method Description IE F O W3C

data Sets or returns the text of this node 6 1 No Yes

length Returns the length of the CDATA 6 1 No Yes


section

CDATASection Object Methods


Method Description IE F O W3C

appendData() Appends data to the node 6 1 No Yes

deleteData() Deletes data from the node 6 1 No Yes

insertData() Inserts data into the node 6 1 No Yes

replaceData() Replaces data in the node 6 1 No Yes

splitText() Splits the CDATA node into two nodes 6 1 No

substringData() Extracts data from the node 6 1 No Yes

The XMLHttpRequest Object


Method Description
abort() Cancels the current request

59
getAllResponseHeaders() Returns the complete set of http headers as a string

getResponseHeader("headername") Returns the value of the specified http header

open("method","URL",async,"uname","pswd") Specifies the method, URL, and other optional


attributes of a request

The method parameter can have a value of "GET",


"POST", or "PUT" (use "GET" when requesting data
and use "POST" when sending data (especially if the
length of the data is greater than 512 bytes.

The URL parameter may be either a relative or


complete URL.

The async parameter specifies whether the request


should be handled asynchronously or not. true
means that script processing carries on after the
send() method, without waiting for a response. false
means that the script waits fo
send(content) Sends the request

setRequestHeader("label","value") Adds a label/value pair to the http header to be sent

Properties
Property Description
onreadystatechange An event handler for an event that fires at every
state change

readyState Returns the state of the object:

0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
responseText Returns the response as a string

responseXML Returns the response as XML. This property returns


an XML document object, which can be examined
and parsed using W3C DOM node tree methods and
properties
status Returns the status as a number (e.g. 404 for "Not
Found" or 200 for "OK")

statusText Returns the status as a string (e.g. "Not Found" or


"OK")

XML DOM Parse Error Object


Microsoft's parseError object can be used to retrieve error information from the Microsoft XML parser.
To see how Firefox handles parser errors, check out the next page of this tutorial.

The parseError Object


When trying to open an XML document, a parser-error may occur.

60
With the parseError object, you can retrieve the error code, the error text, the line that caused the error, and
more.
Note: The parseError object is not a part of the W3C DOM standard!

File Error
In the following code we will try to load a non-existing file, and display some of its error properties:
ExamplexmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load("ksdjf.xml");
document.write("Error code: " + xmlDoc.parseError.errorCode);
document.write("<br />Error reason: " + xmlDoc.parseError.reason);
document.write("<br />Error line: " + xmlDoc.parseError.line);

Code:
<html><body>
<script type="text/javascript">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load("ksdjf.xml");
document.write("Error code: " + xmlDoc.parseError.errorCode);
document.write("<br />Error reason: " + xmlDoc.parseError.reason);
document.write("<br />Error line: " + xmlDoc.parseError.line);
</script>
</body></html>

XML Error
In the following code we let the parser load an XML document that is not well-formed.
(You can read more about well-formed and valid XML in our XML tutorial)ExamplexmlDoc=new
ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load("note_error.xml");
document.write("Error code: " + xmlDoc.parseError.errorCode);
document.write("<br />Error reason: " + xmlDoc.parseError.reason);
document.write("<br />Error line: " + xmlDoc.parseError.line);

Code:
<html><body>
<script type="text/javascript">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load("note_error.xml");
document.write("Error code: " + xmlDoc.parseError.errorCode);
document.write("<br />Error reason: " + xmlDoc.parseError.reason);
document.write("<br />Error line: " + xmlDoc.parseError.line);
</script>
</body></html>

The parseError Object's Properties


Property Description

errorCode Returns a long integer error code

reason Returns a string containing the reason for the error

line Returns a long integer representing the line number for the error

linepos Returns a long integer representing the line position for the error

srcText Returns a string containing the line that caused the error

url Returns the URL pointing the loaded document

61
filepos Returns a long integer file position of the error

XML DOM Parser Errors


When Firefox encounter a parser error, it loads an XML document containing the error

Parser Error in Firefox


When trying to open an XML document, a parser-error may occur.
Unlike Internet Explorer, if Firefox encounters an error, it loads an XML document containing the error
description.
The root node name of the XML error document is "parsererror". This is used to check if there is an error.

XML Error
In the following code we let the parser load an XML document that is not well-formed.
(You can read more about well-formed and valid XML in our XML
tutorial)ExamplexmlDoc=document.implementation.createDocument("","",null);
xmlDoc.async=false;
xmlDoc.load("note_error.xml");
if (xmlDoc.documentElement.nodeName=="parsererror")
{
errStr=xmlDoc.documentElement.childNodes[0].nodeValue;
errStr=errStr.replace(/</g, "&lt;");
document.write(errStr);
}
else
{
document.write("XML is valid");
}

Example explained:
1. Load the xml file
2. Check if the nodeName of the root node is "parsererror"
3. Load the error string into a variable "errStr"
4. Replace "<" characters with "&lt;" before the error string can be written as HTML
Note: Only Internet Explorer will actually check your XML against the DTD. Firefox will not.

Cross Browser Error Check


Here we have created an XML load function that checks for parser errors in both Internet Explorer and
Firefox:Examplefunction loadXMLDocErr(dname)
{
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(dname);

if (xmlDoc.parseError.errorCode != 0)
{
alert("Error in line " + xmlDoc.parseError.line +
" position " + xmlDoc.parseError.linePos +
"\nError Code: " + xmlDoc.parseError.errorCode +
"\nError Reason: " + xmlDoc.parseError.reason +
"Error Line: " + xmlDoc.parseError.srcText);
return(null);
}
}
catch(e)
{
try //Firefox
{
xmlDoc=document.implementation.createDocument("","",null);

62
xmlDoc.async=false;
xmlDoc.load(dname);
if (xmlDoc.documentElement.nodeName=="parsererror")
{
alert(xmlDoc.documentElement.childNodes[0].nodeValue);
return(null);
}
}
catch(e) {alert(e.message)}
}
try
{
return(xmlDoc);
}
catch(e) {alert(e.message)}
return(null);
}

Example explained - Internet Explorer:


1. The first line creates an empty Microsoft XML document object
2. The second line turns off asynchronized loading, to make sure that the parser will not continue
execution of the script before the document is fully loaded
3. The third line tells the parser to load an XML document called "note_error.xml". If the errorCode
property of the parseError object is different from "0", alert the error and exit the function
If the errorCode property is "0", return the XML document

Example explained - Firefox:


1. The first line creates an empty XML document object.
2. The second line turns off asynchronized loading, to make sure that the parser will not continue
execution of the script before the document is fully loaded.
3. The third line tells the parser to load an XML document called "note_error.xml".
4. If the returned document is an error document, alert the error and exit the function. If not, return the
XML document

XML DOM Summary


The XML DOM defines a standard for accessing and manipulating XML.
According to the DOM, everything in an XML document is a node.
The text of an element node is stored in a text node.
The XML DOM views an XML document as a tree-structure. The tree structure is called a node-tree.
In a node tree, the terms parent, child, and sibling are used to describe the relationships.
All modern browsers have a build-in XML parser that can be used to read and manipulate XML.
With the XML DOM properties and methods, you can access every node in an XML document.
Important node properties: nodeName, nodeValue, and nodeType.
When using properties or methods like childNodes or getElementsByTagName(), a node list object is
returned.
Different browsers treat new line, or space characters, between nodes differently.
To ignore empty text nodes between element nodes, you can check the node type.
Nodes can be navigated using node relationships.

63
By: DataIntegratedEntity22592
Source: http://w3schools.com/dom/default.asp

64

Vous aimerez peut-être aussi