Professional Documents
Culture Documents
XML Dom Tutorial
XML Dom Tutorial
In other words:
The XML DOM is a standard for how to get, change, add, or delete XML elements.
DOM Nodes
According to the DOM, everything in an XML document is a node.
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!
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
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.
Examples
W3Schools examples are browser and platform independent. These examples work in all modern browsers.
Result:
xmlDoc is loaded, ready for use
4
text=text+"</book>";
text=text+"</bookstore>";
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.
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>
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>";
Note: Internet Explorer uses the loadXML() method to parse an XML string, while other browsers uses the
DOMParser object.
7
The function above can be stored in the <head> section of an HTML page, and called from a script in the
page.
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".
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.
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").
9
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.
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.
10
document.write(xmlDoc.getElementsByTagName("year")
[0].childNodes[0].nodeValue);
Output:
Everyday Italian
Giada De Laurentiis
2005
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
<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
<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
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).
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
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;
}
14
The examples below use the XML file books.xml.
A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.
<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
<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
<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.
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 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.
Examples
The examples below use the XML file books.xml.
A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.
<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
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
<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
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".
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)
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
Examples
The examples below use the XML file books.xml.
A function, loadXMLString(), in an external JavaScript is used to load the XML string.
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
Examples
The examples below use the XML file books.xml.
A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.
<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
<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
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
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
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.
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.
<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
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"
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()
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
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:
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"
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"
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
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.
<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:
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:
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
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
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
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
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.
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
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
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
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
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
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.
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.
*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
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
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.
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>
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>
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>
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;
Result:
The TO element contains: Tove
44
%>
You send the result back to the client using the response.write 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.
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)
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
47
CDATASection Represents a CDATA section in a document None
(text that will NOT be parsed by a parser)
Comment Represents a comment None
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)
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
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
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
50
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard)
51
firstChild Returns the first child node of the document 5 1 9 Yes
52
name and namespace, and returns the new Attr
object
53
normalizeDocument() No Yes
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)
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)
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
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
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
58
appendData() Appends data to the node 6 1 9 Yes
59
getAllResponseHeaders() Returns the complete set of http headers as a string
Properties
Property Description
onreadystatechange An event handler for an event that fires at every
state change
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
responseText Returns the response as a string
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>
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
61
filepos Returns a long integer file position of the 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, "<");
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 "<" before the error string can be written as HTML
Note: Only Internet Explorer will actually check your XML against the DTD. Firefox will not.
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);
}
63
By: DataIntegratedEntity22592
Source: http://w3schools.com/dom/default.asp
64