Xml Dom Tutorial

  • July 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Xml Dom Tutorial as PDF for free.

More details

  • Words: 15,272
  • Pages: 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): Everyday Italian Giada De Laurentiis

1

2005 <price>30.00
Harry Potter J K. Rowling 2005 <price>29.99 XQuery Kick Start James McGovern Per Bothner Kurt Cagle James Linn Vaidyanathan Nagarajan 2003 <price>49.99 Learning XML Erik T. Ray 2003 <price>39.95
The root node in the XML above is named . All other nodes in the document are contained within . The root node holds four nodes. The first node holds four nodes: , <author rel="nofollow">, <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!<br /> <br /> 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:<br /> <br /> 2<br /> <br /> 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:<br /> <br /> 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.<br /> <br /> 3<br /> <br /> First Child - Last Child Look at the following XML fragment:<bookstore> <book category="cooking"> <title lang="en">Everyday Italian Giada De Laurentiis 2005 <price>30.00 In the XML above, the 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 rel="nofollow">, <year>, and <price> elements.<br /> <br /> 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"; text=text+"Giada De Laurentiis"; text=text+"2005";

4

text=text+""; text=text+"
"; 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)} 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 <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)} 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 <script type="text/javascript"> text="" text=text+"";

6

text=text+"Everyday Italian"; text=text+"Giada De Laurentiis"; text=text+"2005"; text=text+"
"; text=text+"
"; 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"); 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 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 section of an HTML page, and loadXMLDoc() can be called from a script in the page:Example <script type="text/javascript" src="loadxmldoc.js"> <script type="text/javascript"> xmlDoc=loadXMLDoc("books.xml"); document.write("xmlDoc is loaded, ready for use"); 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 <script type="text/javascript" src="loadxmldoc.js">

8

<script type="text/javascript"> xmlDoc=loadXMLDoc("books.xml"); document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue); document.write("
"); document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue); document.write("
"); document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeValue); Result: Everyday Italian Giada De Laurentiis 2005 • Load and parse an XML string <script type="text/javascript" src="loadxmlstring.js"> <script type="text/javascript"> text="" text=text+""; text=text+"Everyday Italian"; text=text+"Giada De Laurentiis"; text=text+"2005"; text=text+""; text=text+""; xmlDoc=loadXMLString(text); document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue); document.write("
"); document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue); document.write("
"); document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeValue); 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 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"; text=text+"Giada De Laurentiis"; text=text+"2005"; text=text+""; text=text+"
"; xmlDoc=loadXMLString(text); document.write(xmlDoc.getElementsByTagName("title") [0].childNodes[0].nodeValue); document.write("
"); document.write(xmlDoc.getElementsByTagName("author") [0].childNodes[0].nodeValue); document.write("
");

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 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<br /> <br /> 11<br /> <br /> • 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><br /> <br /> 12<br /> <br /> </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);<br /> <br /> 13<br /> <br /> 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. 2. 3. 4. 5. 6. 7.<br /> <br /> Load "books.xml" into xmlDoc using loadXMLDoc() Get the child nodes of the first book element Set the "y" variable to be the first child node of the first book element For each child node (starting with the first child node "y"): Check the node type. If the node type is "1" it is an element node Output the name of the node if it is an element node Set the "y" variable to be the next sibling node, and run through the loop again<br /> <br /> XML DOM Node Information The node properties: nodeName, nodeValue, and nodeType. Examples<br /> <br /> 14<br /> <br /> 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><br /> <br /> 15<br /> <br /> 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<br /> <br /> 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<br /> <br /> 16<br /> <br /> 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 Element Attribute Text Comment Document<br /> <br /> NodeType 1 2 3 8 9<br /> <br /> 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"<br /> <br /> 17<br /> <br /> <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".<br /> <br /> <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.<br /> <br /> • •<br /> <br /> 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.<br /> <br /> 18<br /> <br /> The following image represents a node list of the <title> elements in "books.xml":<br /> <br /> 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".<br /> <br /> 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<br /> <br /> 19<br /> <br /> 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<br /> <br /> 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<br /> <br /> 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"; text=text+"Giada De Laurentiis"; text=text+"2005"; text=text+""; 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("
"); } 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 <script type="text/javascript" src="loadxmldoc.js"> <script type="text/javascript"> xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.documentElement.childNodes; document.write("Number of child nodes: " + x.length); Result: Number of child nodes: 9 • Ignore empty text between nodes This example checks the nodeType of the nodes and only processes element nodes <script type="text/javascript" src="loadxmldoc.js">

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("
"); } } 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: Everyday Italian Giada De Laurentiis 2005 <price>30.00 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("
"); } } 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 <script type="text/javascript" src="loadxmldoc.js"> <script type="text/javascript"> xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("book")[0]; document.write(x.parentNode.nodeName); 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

<script type="text/javascript" src="loadxmldoc.js"> <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; }

23

<script type="text/javascript"> xmlDoc=loadXMLDoc("books.xml"); x=get_firstChild(xmlDoc.getElementsByTagName("book")[0]); document.write(x.nodeName); 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 : ExamplexmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("book")[0]; document.write(x.parentNode.nodeName);

Example explained:

24

1. 2. 3. 4.

Load "books.xml" into xmlDoc using loadXMLDoc() Get the first element Output the node name of the parent node of "x" 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 :Example <script type="text/javascript" src="loadxmldoc.js"> <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 type="text/javascript"> xmlDoc=loadXMLDoc("books.xml"); x=get_firstChild(xmlDoc.getElementsByTagName("book")[0]); document.write(x.nodeName); Output: title Example explained: 1. Load "books.xml" into xmlDoc using loadXMLDoc() 2. Use the get_firstChild fucntion on the first 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 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.<br /> <br /> 26<br /> <br /> 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<br /> <br /> 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");<br /> <br /> 27<br /> <br /> 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"<br /> <br /> 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><br /> <br /> 28<br /> <br /> </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><br /> <br /> 29<br /> <br /> <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");<br /> <br /> 30<br /> <br /> 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<br /> <br /> 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<br /> <br /> 31<br /> <br /> 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);<br /> <br /> 32<br /> <br /> 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<br /> <br /> 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);<br /> <br /> 33<br /> <br /> 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><br /> <br /> 34<br /> <br /> 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><br /> <br /> 35<br /> <br /> 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<br /> <br /> 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><br /> <br /> 36<br /> <br /> 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: ");<br /> <br /> 37<br /> <br /> 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<br /> <br /> XML DOM Clone Nodes Copy a Node<br /> <br /> •<br /> <br /> 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 />"); } •<br /> <br /> Code:<br /> <br /> 38<br /> <br /> <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]; 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<br /> <br /> 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<br /> <br /> 39<br /> <br /> 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 // ...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. •<br /> <br /> Load a textfile into a div element with XML HTTP<br /> <br /> 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"); }<br /> <br /> 40<br /> <br /> 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('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> •<br /> <br /> Make a HEAD request with XML HTTP<br /> <br /> 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)<br /> <br /> 41<br /> <br /> {// 4 = "loaded" 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><br /> <br /> 42<br /> <br /> </head><body> <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> •<br /> <br /> List data from an XML file with XML HTTP<br /> <br /> 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"); {<br /> <br /> 43<br /> <br /> try { 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<br /> <br /> 44<br /> <br /> response.write(name) %> 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.<br /> <br /> 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. •<br /> <br /> Display nodeName and nodeType of all elements<br /> <br /> 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)<br /> <br /> 45<br /> <br /> 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: 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) •<br /> <br /> Display nodeName and nodeValue of all elements<br /> <br /> 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)<br /> <br /> 46<br /> <br /> { 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 rootElement (max. one), node of the DOM tree) ProcessingInstruction, Comment, DocumentType DocumentFragment<br /> <br /> Represents a "lightweight" Document object, which can hold a portion of a document<br /> <br /> Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference<br /> <br /> DocumentType<br /> <br /> Provides an interface to the entities defined for the document<br /> <br /> None<br /> <br /> ProcessingInstruction<br /> <br /> Represents a processing instruction<br /> <br /> None<br /> <br /> EntityReference<br /> <br /> Represents an entity reference<br /> <br /> Element<br /> <br /> Represents an element<br /> <br /> Attr<br /> <br /> Represents an attribute<br /> <br /> Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference Text, EntityReference<br /> <br /> 47<br /> <br /> Text<br /> <br /> Represents textual content in an element or attribute<br /> <br /> None<br /> <br /> CDATASection<br /> <br /> Represents a CDATA section in a document (text that will NOT be parsed by a parser)<br /> <br /> None<br /> <br /> Comment<br /> <br /> Represents a comment<br /> <br /> None<br /> <br /> Entity<br /> <br /> Represents an entity<br /> <br /> Notation<br /> <br /> Represents a notation declared in the DTD<br /> <br /> Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference None<br /> <br /> 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<br /> <br /> #document fragment<br /> <br /> null<br /> <br /> DocumentType<br /> <br /> doctype name<br /> <br /> null<br /> <br /> EntityReference<br /> <br /> entity reference name<br /> <br /> null<br /> <br /> Element<br /> <br /> element name<br /> <br /> null<br /> <br /> Attr<br /> <br /> attribute name<br /> <br /> attribute value<br /> <br /> ProcessingInstruction<br /> <br /> target<br /> <br /> content of node<br /> <br /> Comment<br /> <br /> #comment<br /> <br /> comment text<br /> <br /> Text<br /> <br /> #text<br /> <br /> content of node<br /> <br /> CDATASection<br /> <br /> #cdata-section<br /> <br /> content of node<br /> <br /> Entity<br /> <br /> entity name<br /> <br /> null<br /> <br /> Notation<br /> <br /> notation name<br /> <br /> null<br /> <br /> 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<br /> <br /> XML DOM - The Node Object The Node object represents a node in the document tree.<br /> <br /> 48<br /> <br /> The Node Object The Node object is the primary data type for the entire DOM. 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<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> baseURI<br /> <br /> Returns the absolute base URI of a node<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> childNodes<br /> <br /> Returns a NodeList of child nodes for a node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> firstChild<br /> <br /> Returns the first child of a node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> lastChild<br /> <br /> Returns the last child of a node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> localName<br /> <br /> Returns the local part of the name of a node<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> namespaceURI<br /> <br /> Returns the namespace URI of a node<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> nextSibling<br /> <br /> Returns the node immediately following a node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> nodeName<br /> <br /> Returns the name of a node, depending on its type<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> nodeType<br /> <br /> Returns the type of a node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> nodeValue<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> parentNode<br /> <br /> Sets or returns the value of a node, depending on its type Returns the root element (document object) for a node Returns the parent node of a node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> prefix<br /> <br /> Sets or returns the namespace prefix of a node<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> previousSibling<br /> <br /> Returns the node immediately before a node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> textContent<br /> <br /> Sets or returns the textual content of a node and its descendants Returns the text of a node and its descendants. IEonly property Returns the XML of a node and its descendants. IE-only property<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> 5<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> 5<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> ownerDocument<br /> <br /> text xml Node Object Methods Method<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> appendChild()<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> cloneNode()<br /> <br /> Adds a new child node to the end of the list of children of a node Clones a node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> compareDocumentPosition()<br /> <br /> Compares the document position of two nodes<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> getFeature(feature,version)<br /> <br /> Returns a DOM object which implements the specialized APIs of the specified feature and version Returns the object associated to a key on a this node. The object must first have been set to this<br /> <br /> No<br /> <br /> Yes<br /> <br /> No<br /> <br /> Yes<br /> <br /> getUserData(key)<br /> <br /> 49<br /> <br /> node by calling setUserData with the same key hasAttributes()<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> Yes<br /> <br /> isEqualNode()<br /> <br /> Returns true if a node has any attributes, otherwise it returns false Returns true if a node has any child nodes, otherwise it returns false Inserts a new child node before an existing child node Returns whether the specified namespaceURI is the default Checks if two nodes are equal<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> Yes<br /> <br /> isSameNode()<br /> <br /> Checks if two nodes are the same node<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> isSupported(feature,version)<br /> <br /> 9<br /> <br /> Yes<br /> <br /> removeChild()<br /> <br /> Returns whether a specified feature is supported on a node Returns the namespace URI matching a specified prefix Returns the prefix matching a specified namespace URI Puts all text nodes underneath a node (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 Removes a child node<br /> <br /> replaceChild()<br /> <br /> Replaces a child node<br /> <br /> setUserData(key,data,handler)<br /> <br /> Associates an object to a key on a node<br /> <br /> hasChildNodes() insertBefore() isDefaultNamespace(URI)<br /> <br /> lookupNamespaceURI() lookupPrefix() normalize()<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> Yes<br /> <br /> 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<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> length<br /> <br /> Returns the number of nodes in a node list<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> NodeList Object Methods Method<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> Returns the node at the specified index in a node list<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> item()<br /> <br /> XML DOM - The NamedNodeMap Object The NamedNodeMap object represents an unordered list of nodes. The NamedNodeMap object<br /> <br /> 50<br /> <br /> 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. IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard) NamedNodeMap Object Properties Property Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> length<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> Returns the number of nodes in a node list<br /> <br /> NamedNodeMap Object Methods Method<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> getNamedItem()<br /> <br /> Returns the specified node (by name)<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> getNamedItemNS()<br /> <br /> 9<br /> <br /> Yes<br /> <br /> item()<br /> <br /> Returns the specified node (by name and namespace) Returns the node at the specified index<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> removeNamedItem()<br /> <br /> Removes the specified node (by name)<br /> <br /> 6<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> removeNamedItemNS()<br /> <br /> Removes the specified node (by name and namespace) Sets the specified node (by name)<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 9<br /> <br /> Yes<br /> <br /> Sets the specified node (by name and namespace)<br /> <br /> 9<br /> <br /> Yes<br /> <br /> setNamedItem() setNamedItemNS()<br /> <br /> 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<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> async<br /> <br /> Specifies whether downloading of an XML file should be handled asynchronously or not<br /> <br /> 5<br /> <br /> 1.5<br /> <br /> 9<br /> <br /> No<br /> <br /> childNodes<br /> <br /> Returns a NodeList of child nodes for the document<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> doctype<br /> <br /> Returns the Document Type Declaration associated with the document<br /> <br /> 6<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 51<br /> <br /> documentElement<br /> <br /> Returns the root node of the document<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> documentURI<br /> <br /> Sets or returns the location of the document<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> domConfig<br /> <br /> Returns the configuration used when normalizeDocument() is invoked<br /> <br /> No<br /> <br /> Yes<br /> <br /> firstChild<br /> <br /> Returns the first child node of the document<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> implementation<br /> <br /> Returns the DOMImplementation object that handles this document<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> inputEncoding<br /> <br /> Returns the encoding used for the document (when parsing)<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> lastChild<br /> <br /> Returns the last child node of the document<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> nodeName<br /> <br /> Returns the name of a node (depending on its type)<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> nodeType<br /> <br /> Returns the node type of a node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> nodeValue<br /> <br /> Sets or returns the value of a node (depending on its type)<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> strictErrorChecking<br /> <br /> Sets or returns whether error-checking is enforced or not<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> text<br /> <br /> Returns the text of a node and its descendants. IE-only property<br /> <br /> 5<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> xml<br /> <br /> Returns the XML of a node and its descendants. IE-only property<br /> <br /> 5<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> xmlEncoding<br /> <br /> Returns the XML encoding of the document<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> xmlStandalone<br /> <br /> Sets or returns whether the document is standalone<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> xmlVersion<br /> <br /> Sets or returns the XML version of the document<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> Document Object Methods<br /> <br /> 52<br /> <br /> Method<br /> <br /> Description<br /> <br /> IE<br /> <br /> adoptNode(sourcenode)<br /> <br /> Adopts a node from another document to this document, and returns the adopted node<br /> <br /> createAttribute(name)<br /> <br /> Creates an attribute node with the specified name, and returns the new Attr object<br /> <br /> O<br /> <br /> W3C<br /> <br /> No<br /> <br /> Yes<br /> <br /> 9<br /> <br /> Yes<br /> <br /> createAttributeNS(uri,name)<br /> <br /> Creates an attribute node with the specified name and namespace, and returns the new Attr object<br /> <br /> 9<br /> <br /> Yes<br /> <br /> createCDATASection()<br /> <br /> Creates a CDATA section node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> createComment()<br /> <br /> Creates a comment node<br /> <br /> 6<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> createDocumentFragment()<br /> <br /> Creates an empty DocumentFragment object, and returns it<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> createElement()<br /> <br /> Creates an element node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> createElementNS()<br /> <br /> Creates an element node with a specified namespace<br /> <br /> No<br /> <br /> 9<br /> <br /> Yes<br /> <br /> createEntityReference(name)<br /> <br /> Creates an EntityReference object, and returns it<br /> <br /> 5<br /> <br /> No<br /> <br /> Yes<br /> <br /> createProcessingInstruction(target,d ata)<br /> <br /> Creates a ProcessingInstruction object, and returns it<br /> <br /> 5<br /> <br /> 9<br /> <br /> Yes<br /> <br /> createTextNode()<br /> <br /> Creates a text node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> createElementNS()<br /> <br /> Creates an element node with a specified namespace<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> createEntityReference(name)<br /> <br /> Creates an EntityReference object, and returns it<br /> <br /> 5<br /> <br /> No<br /> <br /> Yes<br /> <br /> createProcessingInstruction(target,d ata)<br /> <br /> Creates a ProcessingInstruction object, and returns it<br /> <br /> 5<br /> <br /> 9<br /> <br /> Yes<br /> <br /> createTextNode()<br /> <br /> Creates a text node<br /> <br /> 5<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 6<br /> <br /> F<br /> <br /> 1<br /> <br /> 1<br /> <br /> 1<br /> <br /> 53<br /> <br /> getElementById(id) normalizeDocument()<br /> <br /> Returns the element that has an ID attribute with the given value. If no such element exists, it returns null Returns NodeList of or allattribute elementsnode with a Renamesa an element specified name<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9 No<br /> <br /> Yes Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9 No<br /> <br /> Yes Yes<br /> <br /> getElementsByTagNameNS()<br /> <br /> Returns a NodeList of all elements with a specified name and namespace<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> importNode(nodetoimport,deep)<br /> <br /> Imports a node from another document to 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<br /> <br /> 9<br /> <br /> Yes<br /> <br /> getElementsByTagName() renameNode()<br /> <br /> 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<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> createDocument(nsURI, name, doctype)<br /> <br /> Creates a new DOM Document object of the specified doctype<br /> <br /> Yes<br /> <br /> createDocumentType(name, pubId, systemId)<br /> <br /> Creates an empty DocumentType node<br /> <br /> Yes<br /> <br /> getFeature(feature, version)<br /> <br /> Returns an object which implements the APIs of the specified feature and version, if the is any<br /> <br /> Yes<br /> <br /> hasFeature(feature, version)<br /> <br /> Checks whether the DOM implementation implements a specific feature and version<br /> <br /> Yes<br /> <br /> 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<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> entities<br /> <br /> 6<br /> <br /> No<br /> <br /> 9<br /> <br /> Yes<br /> <br /> Returns a NamedNodeMap containing the entities declared in the DTD<br /> <br /> 54<br /> <br /> internalSubset<br /> <br /> Returns the internal DTD as a string<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> Yes<br /> <br /> name<br /> <br /> Returns the name of the DTD<br /> <br /> 6<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> notations<br /> <br /> Returns a NamedNodeMap containing the notations declared in the DTD Returns the system identifier of the external DTD<br /> <br /> 6<br /> <br /> No<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> systemId<br /> <br /> XML DOM - The ProcessingInstruction Object The ProcessingInstruction object represents a processing instruction. 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<br /> <br /> data target<br /> <br /> IE<br /> <br /> F<br /> <br /> Sets or returns the content of this processing instruction Returns the target of this processing instruction<br /> <br /> O<br /> <br /> W3C<br /> <br /> No<br /> <br /> Yes<br /> <br /> No<br /> <br /> Yes<br /> <br /> 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<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> Returns a NamedNodeMap of attributes for the element Returns the absolute base URI of the element<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> firstChild<br /> <br /> Returns a NodeList of child nodes for the element Returns the first child of the element<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> lastChild<br /> <br /> Returns the last child of the element<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> localName<br /> <br /> Returns the local part of the name of the element Returns the namespace URI of the element<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> attributes baseURI childNodes<br /> <br /> namespaceURI<br /> <br /> 55<br /> <br /> nextSibling nodeName nodeType ownerDocument parentNode prefix previousSibling schemaTypeInfo tagName textContent text xml Element Object Methods Method appendChild() cloneNode() compareDocumentPosition() getAttribute() getAttributeNS() getAttributeNode() getAttributeNodeNS() getElementsByTagName() getElementsByTagNameNS() getUserData(key)<br /> <br /> hasAttribute() hasAttributeNS() hasAttributes() hasChildNodes()<br /> <br /> Returns the node immediately following the element Returns the name of the node, depending on its type Returns the type of the node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> Returns the root element (document object) for an element Returns the parent node of the element<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> Sets or returns the namespace prefix of the element Returns the node immediately before the element Returns the type information associated with the element Returns the name of the element<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> Sets or returns the text content of the element and its descendants Returns the text of the node and its descendants. IE-only property Returns the XML of the node and its descendants. IE-only property<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> 5<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> 5<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> Adds a new child node to the end of the list of children of the node Clones a node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> Compares the document position of two nodes Returns the value of an attribute<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> Returns the value of an attribute (with a namespace) Returns an attribute node as an Attribute object Returns an attribute node (with a namespace) as an Attribute object Returns a NodeList of matching element nodes, and their children Returns a NodeList of matching element nodes (with a namespace), and their children Returns the object associated to a key on a this node. The object must first have been set to this node by calling setUserData with the same key Returns whether an element has any attributes matching a specified name Returns whether an element has any attributes matching a specified name and namespace Returns whether the element has any attributes Returns whether the element has any child nodes<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 56<br /> <br /> insertBefore()<br /> <br /> 5<br /> <br /> isEqualNode()<br /> <br /> Inserts a new child node before an existing child node Returns whether the specified namespaceURI is the default Checks if two nodes are equal<br /> <br /> No<br /> <br /> isSameNode()<br /> <br /> Checks if two nodes are the same node<br /> <br /> No<br /> <br /> isSupported(feature,version)<br /> <br /> Returns whether a specified feature is supported on the element Returns the namespace URI matching a specified prefix Returns the prefix matching a specified namespace URI Puts all text nodes underneath this 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 Removes a specified attribute<br /> <br /> isDefaultNamespace(URI)<br /> <br /> lookupNamespaceURI()<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> Yes<br /> <br /> No<br /> <br /> No<br /> <br /> Yes<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> removeAttributeNode()<br /> <br /> Removes a specified attribute (with a namespace) Removes a specified attribute node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> removeChild()<br /> <br /> Removes a child node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> replaceChild()<br /> <br /> Replaces a child node<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> setUserData(key,data,handler)<br /> <br /> Associates an object to a key on the element Adds a new attribute<br /> <br /> No<br /> <br /> Yes<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> Yes<br /> <br /> No<br /> <br /> Yes<br /> <br /> No<br /> <br /> Yes<br /> <br /> lookupPrefix() normalize()<br /> <br /> removeAttribute() removeAttributeNS()<br /> <br /> setAttribute() setAttributeNS() setAttributeNode() setAttributeNodeNS(attrnode) setIdAttribute(name,isId)<br /> <br /> setIdAttributeNS(uri,name,isId)<br /> <br /> setIdAttributeNode(idAttr,isId)<br /> <br /> Adds a new attribute (with a namespace) Adds a new attribute node Adds a new attribute node (with a namespace) If the isId property of the Attribute object is true, this method declares the specified attribute to be a userdetermined ID attribute If the isId property of the Attribute object is true, this method declares the specified attribute (with a namespace) to be a user-determined ID attribute If the isId property of the Attribute object is true, this method declares the specified attribute to be a userdetermined ID attribute<br /> <br /> 5<br /> <br /> 5<br /> <br /> 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.<br /> <br /> 57<br /> <br /> 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 baseURI isId localName name namespaceURI nodeName nodeType nodeValue ownerDocument ownerElement prefix schemaTypeInfo specified textContent text value xml<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> Returns the absolute base URI of the attribute Returns true if the attribute is known to be of type ID, otherwise it returns false Returns the local part of the name of the attribute Returns the name of the attribute<br /> <br /> No<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> Yes<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> Returns the namespace URI of the attribute Returns the name of the node, depending on its type Returns the type of the node<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> Sets or returns the value of the node, depending on its type Returns the root element (document object) for an attribute Returns the element node the attribute is attached to Sets or returns the namespace prefix of the attribute Returns the type information associated with this attribute Returns true if the attribute value is set in the document, and false if it's a default value in a DTD/Schema. Sets or returns the textual content of an attribute Returns the text of the attribute. IE-only property Sets or returns the value of the attribute<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> Yes<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 5<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> 5<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> Returns the XML of the attribute. IEonly property<br /> <br /> 5<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> 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)<br /> <br /> Text Object Properties Method data isElementContentWhitespace<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> Sets or returns the text of the element or attribute Returns true if the text node contains content whitespace, otherwise it returns<br /> <br /> 6<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> Yes<br /> <br /> 58<br /> <br /> false length<br /> <br /> Returns the length of the text of the element or attribute Returns all text of text nodes adjacent to this node, concatenated in document order<br /> <br /> 6<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> Yes<br /> <br /> Text Object Methods Method<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> appendData()<br /> <br /> Appends data to the node<br /> <br /> 6<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> deleteData()<br /> <br /> Deletes data from the node<br /> <br /> 6<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> insertData()<br /> <br /> Inserts data into the node<br /> <br /> 6<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> replaceData()<br /> <br /> Replaces data in the node<br /> <br /> 6<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> replaceWholeText(text)<br /> <br /> Replaces the text of this node and all adjacent text nodes with the specified text Splits this node into two nodes at the specified offset, and returns the new node that contains the text after the offset Extracts data from the node<br /> <br /> No<br /> <br /> No<br /> <br /> No<br /> <br /> Yes<br /> <br /> 6<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> 6<br /> <br /> 1<br /> <br /> 9<br /> <br /> Yes<br /> <br /> wholeText<br /> <br /> splitText()<br /> <br /> substringData()<br /> <br /> 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<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> data<br /> <br /> Sets or returns the text of this node<br /> <br /> 6<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> length<br /> <br /> Returns the length of the CDATA section<br /> <br /> 6<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> CDATASection Object Methods Method<br /> <br /> Description<br /> <br /> IE<br /> <br /> F<br /> <br /> O<br /> <br /> W3C<br /> <br /> appendData()<br /> <br /> Appends data to the node<br /> <br /> 6<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> deleteData()<br /> <br /> Deletes data from the node<br /> <br /> 6<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> insertData()<br /> <br /> Inserts data into the node<br /> <br /> 6<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> replaceData()<br /> <br /> Replaces data in the node<br /> <br /> 6<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> 59<br /> <br /> splitText()<br /> <br /> Splits the CDATA node into two nodes<br /> <br /> 6<br /> <br /> 1<br /> <br /> No<br /> <br /> substringData()<br /> <br /> Extracts data from the node<br /> <br /> 6<br /> <br /> 1<br /> <br /> No<br /> <br /> Yes<br /> <br /> The XMLHttpRequest Object Method<br /> <br /> Description<br /> <br /> abort()<br /> <br /> Cancels the current request<br /> <br /> getAllResponseHeaders()<br /> <br /> Returns the complete set of http headers as a string<br /> <br /> getResponseHeader("headername")<br /> <br /> Returns the value of the specified http header<br /> <br /> open("method","URL",async,"uname","pswd")<br /> <br /> 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.<br /> <br /> send(content)<br /> <br /> 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 Sends the request<br /> <br /> setRequestHeader("label","value")<br /> <br /> Adds a label/value pair to the http header to be sent<br /> <br /> Properties Property<br /> <br /> Description<br /> <br /> onreadystatechange<br /> <br /> An event handler for an event that fires at every state change<br /> <br /> readyState<br /> <br /> Returns the state of the object:<br /> <br /> responseText<br /> <br /> 0 = uninitialized 1 = loading 2 = loaded 3 = interactive 4 = complete Returns the response as a string<br /> <br /> responseXML<br /> <br /> status<br /> <br /> 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 Returns the status as a number (e.g. 404 for "Not Found" or 200 for "OK")<br /> <br /> 60<br /> <br /> statusText<br /> <br /> Returns the status as a string (e.g. "Not Found" or "OK")<br /> <br /> 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. 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<br /> <br /> 61<br /> <br /> Property<br /> <br /> Description<br /> <br /> errorCode<br /> <br /> Returns a long integer error code<br /> <br /> reason<br /> <br /> Returns a string containing the reason for the error<br /> <br /> line<br /> <br /> Returns a long integer representing the line number for the error<br /> <br /> linepos<br /> <br /> Returns a long integer representing the line position for the error<br /> <br /> srcText<br /> <br /> Returns a string containing the line that caused the error<br /> <br /> url<br /> <br /> Returns the URL pointing the loaded document<br /> <br /> filepos<br /> <br /> Returns a long integer file position of the error<br /> <br /> 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, "<"); 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. 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 +<br /> <br /> 62<br /> <br /> " 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); 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<br /> <br /> 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.<br /> <br /> 63<br /> <br /> By: DataIntegratedEntity22592 Source: http://w3schools.com/dom/default.asp<br /> <br /> 64 </div> </div> <hr /> <h4>Related Documents</h4> <div class="row"> <div class="col-lg-2 col-md-4 col-sm-6 col-6"> <div class="card item-doc mb-4"> <a href="https://pdfcoke.com/documents/xml-dom-tutorial-gl3gjll6ek3p" class="d-block"><img class="card-img-top" src="https://pdfcoke.com/img/crop/300x300/gl3gjll6ek3p.jpg" alt=""/></a> <div class="card-body text-left"> <h5 class="card-title"><a href="https://pdfcoke.com/documents/xml-dom-tutorial-gl3gjll6ek3p" class="text-dark">Xml Dom Tutorial</a></h5> <small class="text-muted float-left"><i class="fas fa-clock"></i> July 2020</small> <small class="text-muted float-right"><i class="fas fa-eye"></i> 3</small> <div class="clearfix"></div> </div> </div> </div> <div class="col-lg-2 col-md-4 col-sm-6 col-6"> <div class="card item-doc mb-4"> <a href="https://pdfcoke.com/documents/xml-dom-r6zw1ewwnq30" class="d-block"><img class="card-img-top" src="https://pdfcoke.com/img/crop/300x300/r6zw1ewwnq30.jpg" alt=""/></a> <div class="card-body text-left"> <h5 class="card-title"><a href="https://pdfcoke.com/documents/xml-dom-r6zw1ewwnq30" class="text-dark">Xml Dom</a></h5> <small class="text-muted float-left"><i class="fas fa-clock"></i> May 2020</small> <small class="text-muted float-right"><i class="fas fa-eye"></i> 15</small> <div class="clearfix"></div> </div> </div> </div> <div class="col-lg-2 col-md-4 col-sm-6 col-6"> <div class="card item-doc mb-4"> <a href="https://pdfcoke.com/documents/xml-dom-q6zp9mdp143p" class="d-block"><img class="card-img-top" src="https://pdfcoke.com/img/crop/300x300/q6zp9mdp143p.jpg" alt=""/></a> <div class="card-body text-left"> <h5 class="card-title"><a href="https://pdfcoke.com/documents/xml-dom-q6zp9mdp143p" class="text-dark">Xml Dom</a></h5> <small class="text-muted float-left"><i class="fas fa-clock"></i> December 2019</small> <small class="text-muted float-right"><i class="fas fa-eye"></i> 16</small> <div class="clearfix"></div> </div> </div> </div> <div class="col-lg-2 col-md-4 col-sm-6 col-6"> <div class="card item-doc mb-4"> <a href="https://pdfcoke.com/documents/xml-tutorial-g0ox9mmxp5o6" class="d-block"><img class="card-img-top" src="https://pdfcoke.com/img/crop/300x300/g0ox9mmxp5o6.jpg" alt=""/></a> <div class="card-body text-left"> <h5 class="card-title"><a href="https://pdfcoke.com/documents/xml-tutorial-g0ox9mmxp5o6" class="text-dark">Xml Tutorial</a></h5> <small class="text-muted float-left"><i class="fas fa-clock"></i> May 2020</small> <small class="text-muted float-right"><i class="fas fa-eye"></i> 3</small> <div class="clearfix"></div> </div> </div> </div> <div class="col-lg-2 col-md-4 col-sm-6 col-6"> <div class="card item-doc mb-4"> <a href="https://pdfcoke.com/documents/xml-tutorial-263edqq26ko0" class="d-block"><img class="card-img-top" src="https://pdfcoke.com/img/crop/300x300/263edqq26ko0.jpg" alt=""/></a> <div class="card-body text-left"> <h5 class="card-title"><a href="https://pdfcoke.com/documents/xml-tutorial-263edqq26ko0" class="text-dark">Xml Tutorial</a></h5> <small class="text-muted float-left"><i class="fas fa-clock"></i> July 2020</small> <small class="text-muted float-right"><i class="fas fa-eye"></i> 3</small> <div class="clearfix"></div> </div> </div> </div> <div class="col-lg-2 col-md-4 col-sm-6 col-6"> <div class="card item-doc mb-4"> <a href="https://pdfcoke.com/documents/xml-tutorial-4vz0qjmwrq38" class="d-block"><img class="card-img-top" src="https://pdfcoke.com/img/crop/300x300/4vz0qjmwrq38.jpg" alt=""/></a> <div class="card-body text-left"> <h5 class="card-title"><a href="https://pdfcoke.com/documents/xml-tutorial-4vz0qjmwrq38" class="text-dark">Xml Tutorial</a></h5> <small class="text-muted float-left"><i class="fas fa-clock"></i> June 2020</small> <small class="text-muted float-right"><i class="fas fa-eye"></i> 0</small> <div class="clearfix"></div> </div> </div> </div> </div> </div> </div> </div> </div> <footer class="footer pt-5 pb-0 pb-md-5 bg-primary text-white"> <div class="container"> <div class="row"> <div class="col-md-3 mb-3 mb-sm-0"> <h5 class="text-white font-weight-bold mb-4">Our Company</h5> <ul class="list-unstyled"> <li><i class="fas fa-location-arrow"></i> 3486 Boone Street, Corpus Christi, TX 78476</li> <li><i class="fas fa-phone"></i> +1361-285-4971</li> <li><i class="fas fa-envelope"></i> <a href="mailto:info@pdfcoke.com" class="text-white">info@pdfcoke.com</a></li> </ul> </div> <div class="col-md-3 mb-3 mb-sm-0"> <h5 class="text-white font-weight-bold mb-4">Quick Links</h5> <ul class="list-unstyled"> <li><a href="https://pdfcoke.com/about" class="text-white">About</a></li> <li><a href="https://pdfcoke.com/contact" class="text-white">Contact</a></li> <li><a href="https://pdfcoke.com/help" class="text-white">Help / FAQ</a></li> <li><a href="https://pdfcoke.com/account" class="text-white">Account</a></li> </ul> </div> <div class="col-md-3 mb-3 mb-sm-0"> <h5 class="text-white font-weight-bold mb-4">Legal</h5> <ul class="list-unstyled"> <li><a href="https://pdfcoke.com/tos" class="text-white">Terms of Service</a></li> <li><a href="https://pdfcoke.com/privacy-policy" class="text-white">Privacy Policy</a></li> <li><a href="https://pdfcoke.com/cookie-policy" class="text-white">Cookie Policy</a></li> <li><a href="https://pdfcoke.com/disclaimer" class="text-white">Disclaimer</a></li> </ul> </div> <div class="col-md-3 mb-3 mb-sm-0"> <h5 class="text-white font-weight-bold mb-4">Follow Us</h5> <ul class="list-unstyled list-inline list-social"> <li class="list-inline-item"><a href="#" class="text-white" target="_blank"><i class="fab fa-facebook-f"></i></a></li> <li class="list-inline-item"><a href="#" class="text-white" target="_blank"><i class="fab fa-twitter"></i></a></li> <li class="list-inline-item"><a href="#" class="text-white" target="_blank"><i class="fab fa-linkedin"></i></a></li> <li class="list-inline-item"><a href="#" class="text-white" target="_blank"><i class="fab fa-instagram"></i></a></li> </ul> <h5 class="text-white font-weight-bold mb-4">Mobile Apps</h5> <ul class="list-unstyled "> <li><a href="#" class="bb-alert" data-msg="IOS app is not available yet! Please try again later!"><img src="https://pdfcoke.com/static/images/app-store-badge.svg" height="45" /></a></li> <li><a href="#" class="bb-alert" data-msg="ANDROID app is not available yet! Please try again later!"><img style="margin-left: -10px;" src="https://pdfcoke.com/static/images/google-play-badge.png" height="60" /></a></li> </ul> </div> </div> </div> </footer> <div class="footer-copyright border-top pt-4 pb-2 bg-primary text-white"> <div class="container"> <p>Copyright © 2024 PDFCOKE.</p> </div> </div> <script src="https://pdfcoke.com/static/javascripts/jquery.min.js"></script> <script src="https://pdfcoke.com/static/javascripts/popper.min.js"></script> <script src="https://pdfcoke.com/static/javascripts/bootstrap.min.js"></script> <script src="https://pdfcoke.com/static/javascripts/bootbox.all.min.js"></script> <script src="https://pdfcoke.com/static/javascripts/filepond.js"></script> <script src="https://pdfcoke.com/static/javascripts/main.js?v=1732474460"></script> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-144986120-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-144986120-1'); </script> </body> </html>