Sie sind auf Seite 1von 161

XML

XML stands for Extensible Markup Language.

XML was designed to transport and store data.

• XML stands for Extensible Markup Language.


• XML is a markup language much like HTML.
• XML was designed to carry data, not to display data.
• XML tags are not predefined. You must define your own tags.

The Difference Between XML and HTML

• XML is not a replacement for HTML.


XML and HTML were designed with different goals:
• XML was designed to transport and store data, with focus on what data is.
HTML was designed to display data, with focus on how data looks.
• HTML is about displaying information, while XML is about carrying information.

XML is used in many aspects of web development, often to simplify data storage and sharing.

XML Separates Data from HTML

If you need to display dynamic data in your HTML document, it will take a lot of work to edit
the HTML each time the data changes.

With XML, data can be stored in separate XML files. This way you can concentrate on using
HTML for layout and display, and be sure that changes in the underlying data will not require
any changes to the HTML.

With a few lines of JavaScript, you can read an external XML file and update the data content of
your HTML.

XML Simplifies Data Sharing

In the real world, computer systems and databases contain data in incompatible formats.

XML data is stored in plain text format. This provides a software- and hardware-independent
way of storing data.
This makes it much easier to create data that different applications can share.

XML Simplifies Data Transport

With XML, data can easily be exchanged between incompatible systems.

One of the most time-consuming challenges for developers is to exchange data between
incompatible systems over the Internet.

Exchanging data as XML greatly reduces this complexity, since the data can be read by different
incompatible applications.

XML Simplifies Platform Changes

Upgrading to new systems (hardware or software platforms), is always very time consuming.
Large amounts of data must be converted and incompatible data is often lost.

XML data is stored in text format. This makes it easier to expand or upgrade to new operating
systems, new applications, or new browsers, without losing data.

XML Makes Your Data More Available

Since XML is independent of hardware, software and application, XML can make your data
more available and useful.

Different applications can access your data, not only in HTML pages, but also from XML data
sources.

With XML, your data can be available to all kinds of "reading machines" (Handheld computers,
voice machines, news feeds, etc), and make it more available for blind people, or people with
other disabilities.

XML is Used to Create New Internet Languages

A lot of new Internet languages are created with XML.

Here are some examples:

• XHTML the latest version of HTML


• WSDL for describing available web services
• WAP and WML as markup languages for handheld devices
• RSS languages for news feeds
• RDF and OWL for describing resources and ontology
• SMIL for describing multimedia for the web

XML Tree

XML documents form a tree structure that starts at "the root" and branches to "the leaves".

An Example XML Document

XML documents use a self-describing and simple syntax:

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The first line is the XML declaration. It defines the XML version (1.0) and the encoding used
(ISO-8859-1 = Latin-1/West European character set).

The next line describes the root element of the document (like saying: "this document is a
note"):

<note>

The next 4 lines describe 4 child elements of the root (to, from, heading, and body):

<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>

And finally the last line defines the end of the root element:

</note>

You can assume, from this example, that the XML document contains a note to Tove from Jani.
Don't you agree that XML is pretty self-descriptive?

XML Documents Form a Tree Structure

XML documents must contain a root element. This element is "the parent" of all other elements.

The elements in an XML document form a document tree. The tree starts at
the root and branches to the lowest level of the tree.

All elements can have sub elements (child elements):

<root>
<child>
<subchild>.....</subchild>
</child>
</root>

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

All elements can have text content and attributes (just like in HTML).

Example:

The image above represents one book in the XML below:

<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurent is</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

The root element in the example is <bookstore>. All <book> elements in the document are
contained within <bookstore>.

The <book> element has 4 children: <title>,< author>, <year>, <price>.

XML Syntax Rules

The syntax rules of XML are very simple and logical. The rules are easy to learn, and easy to
use.

All XML Elements Must Have a Closing Tag

In HTML, you will often see elements that don't have a closing tag:

<p>This is a paragraph
<p>This is another paragraph
In XML, it is illegal to omit the closing tag. All elements must have a closing tag:

<p>This is a paragraph</p>
<p>This is another paragraph</p>

Note: You might have noticed from the previous example that the XML declaration did not have
a closing tag. This is not an error. The declaration is not a part of the XML document itself, and it
has no closing tag.

XML Tags are Case Sensitive

XML elements are defined using XML tags.

XML tags are case sensitive. With XML, the tag <Letter> is different from the tag <letter>.

Opening and closing tags must be written with the same case:

<Message>This is incorrect</message>

<message>This is correct</message>

Note: "Opening and closing tags" are often referred to as "Start and end tags". Use whatever you
prefer. It is exactly the same thing.

XML Elements Must be Properly Nested

In HTML, you will often see improperly nested elements:

<b><i>This text is bold and italic</b></i>

In XML, all elements must be properly nested within each other:

<b><i>This text is bold and italic</i></b>

In the example above, "Properly nested" simply means that since the <i> element is opened
inside the <b> element, it must be closed inside the <b> element.

XML Documents Must Have a Root Element

XML documents must contain one element that is the parent of all other elements. This element
is called the root element.
<root>
<child>
<subchild>.....</subchild>
</child>
</root>

XML Attribute Values Must be Quoted

XML elements can have attributes in name/value pairs just like in HTML.

In XML the attribute value must always be quoted. Study the two XML documents below. The
first one is incorrect, the second is correct:

<note date=12/11/2007>
<to>Tove</to>
<from>Jani</from>
</note>

<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>

The error in the first document is that the date attribute in the note element is not quoted.

Entity References

Some characters have a special meaning in XML.

If you place a character like "<" inside an XML element, it will generate an error because the
parser interprets it as the start of a new element.

This will generate an XML error:

<message>if salary < 1000 then</message>

To avoid this error, replace the "<" character with an entity reference:

<message>if salary &lt; 1000 then</message>


There are 5 predefined entity references in XML:

&lt; < less than

&gt; > greater than

&amp; & ampersand

&apos; ' apostrophe

&quot; " quotation mark

Note: Only the characters "<" and "&" are strictly illegal in XML. The greater than character is
legal, but it is a good habit to replace it.

Comments in XML

The syntax for writing comments in XML is similar to that of HTML.

<!-- This is a comment -->

With XML, White Space is Preserved

HTML reduces multiple white space characters to a single white space:

HTML: Hello my name is Tove

Output: Hello my name is Tove.

With XML, the white space in your document is not truncated.

XML Elements

An XML document contains XML Elements.


What is an XML Element?

An XML element is everything from (including) the element's start tag to (including) the
element's end tag.

An element can contain other elements, simple text or a mixture of both. Elements can also have
attributes.

<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

In the example above, <bookstore> and <book> have element contents, because they contain
other elements. <author> has text content because it contains text.

In the example above only <book> has an attribute (category="CHILDREN").

XML Naming Rules

XML elements must follow these naming rules:

• Names can contain letters, numbers, and other characters


• Names must not start with a number or punctuation character
• Names must not start with the letters xml (or XML, or Xml, etc)
• Names cannot contain spaces

Any name can be used, no words are reserved.

Best Naming Practices


Make names descriptive. Names with an underscore separator are nice: <first_name>,
<last_name>.

Names should be short and simple, like this: <book_title> not like this:
<the_title_of_the_book>.

Avoid "-" characters. If you name something "first-name," some software may think you want to
subtract name from first.

Avoid "." characters. If you name something "first.name," some software may think that "name"
is a property of the object "first."

Avoid ":" characters. Colons are reserved to be used for something called namespaces (more
later).

XML documents often have a corresponding database. A good practice is to use the naming rules
of your database for the elements in the XML documents.

XML Elements are Extensible

XML elements can be extended to carry more information.

Look at the following XML example:

<note>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note>

Let's imagine that we created an application that extracted the <to>, <from>, and <body>
elements from the XML document to produce this output:

MESSAGE

To: Tove
From: Jani

Don't forget me this weekend!

Imagine that the author of the XML document added some extra information to it:

<note>
<date>2008-01-10</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Should the application break or crash?

No. The application should still be able to find the <to>, <from>, and <body> elements in the
XML document and produce the same output.

One of the beauties of XML, is that it can often be extended without breaking applications.

XML Attributes

XML elements can have attributes in the start tag, just like HTML.

Attributes provide additional information about elements.

XML Attributes

From HTML you will remember this: <img src="computer.gif">. The "src" attribute provides
additional information about the <img> element.

In HTML (and in XML) attributes provide additional information about elements:

<img src="computer.gif">
<a href="demo.asp">

Attributes often provide information that is not a part of the data. In the example below, the file
type is irrelevant to the data, but important to the software that wants to manipulate the element:

<file type="gif">computer.gif</file>

XML Attributes Must be Quoted


Attribute values must always be enclosed in quotes, but either single or double quotes can be
used. For a person's sex, the person tag can be written like this:

<person sex="female">

or like this:

<person sex='female'>

If the attribute value itself contains double quotes you can use single quotes, like in this
example:

<gangster name='George "Shotgun" Ziegler'>

or you can use character entities:

<gangster name="George &quot;Shotgun&quot; Ziegler">

XML Elements vs. Attributes

Take a look at these examples:

<person sex="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>

<person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>

In the first example sex is an attribute. In the last, sex is an element. Both examples provide the
same information.

There are no rules about when to use attributes and when to use elements. Attributes are handy in
HTML. In XML my advice is to avoid them. Use elements instead.

My Favorite Way
The following three XML documents contain exactly the same information:

A date attribute is used in the first example:

<note date="10/01/2008">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

A date element is used in the second example:

<note>
<date>10/01/2008</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

An expanded date element is used in the third: (THIS IS MY FAVORITE):

<note>
<date>
<day>10</day>
<month>01</month>
<year>2008</year>
</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Avoid XML Attributes?

Some of the problems with using attributes are:

• attributes cannot contain multiple values (elements can)


• attributes cannot contain tree structures (elements can)
• attributes are not easily expandable (for future changes)
Attributes are difficult to read and maintain. Use elements for data. Use attributes for information
that is not relevant to the data.

Don't end up like this:

<note day="10" month="01" year="2008"


to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!">
</note>

XML Attributes for Metadata

Sometimes ID references are assigned to elements. These IDs can be used to identify XML
elements in much the same way as the ID attribute in HTML. This example demonstrates this:

<messages>
<note id="501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note id="502">
<to>Jani</to>
<from>Tove</from>
<heading>Re: Reminder</heading>
<body>I will not</body>
</note>
</messages>

XML Validation

XML with correct syntax is "Well Formed" XML.

XML validated against a DTD is "Valid" XML.

Well Formed XML Documents

A "Well Formed" XML document has correct XML syntax.

The syntax rules were described in the previous chapters:


• XML documents must have a root element
• XML elements must have a closing tag
• XML tags are case sensitive
• XML elements must be properly nested
• XML attribute values must be quoted

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Valid XML Documents

A "Valid" XML document is a "Well Formed" XML document, which also conforms to the rules
of a Document Type Definition (DTD):

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The DOCTYPE declaration in the example above, is a reference to an external DTD file. The
content of the file is shown in the paragraph below.

XML DTD

The purpose of a DTD is to define the structure of an XML document. It defines the structure
with a list of legal elements:

<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
If you want to study DTD, you will find our DTD tutorial on our homepage.

XML Schema

W3C supports an XML based alternative to DTD called XML Schema:

<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>

</xs:element>

XML Validator

Use our XML validator to syntax-check your XML.

XML Errors Will Stop You

Errors in XML documents will stop your XML applications.

The W3C XML specification states that a program should stop processing an XML document if
it finds an error. The reason is that XML software should be small, fast, and compatible.

HTML browsers will display documents with errors (like missing end tags). HTML browsers are
big and incompatible because they have a lot of unnecessary code to deal with (and display)
HTML errors.

With XML, errors are not allowed.

Syntax-Check Your XML


To help you syntax-check your XML, we have created an XML validator.

Paste your XML into the text area below, and syntax-check it by clicking the "Validate" button.

Note: This only checks if your XML is "Well formed". If you want to validate your XML against
a DTD, see the last paragraph on this page.

Syntax-Check an XML File

You can syntax-check an XML file by typing the URL of the file into the input field below, and
then click the "Validate" button:

Filename:

Note: If you get an "Access denied" error, it's because your browser security does not allow file
access across domains.

The file "note_error.xml" demonstrates your browsers error handling. If you want see an error
free message, substitute the "note_error.xml" with "cd_catalog.xml".

Validate Your XML Against a DTD

If you know DTD, you can validate your XML in the text area below.

Just add the DOCTYPE declaration to your XML and click the "Validate" button:

Viewing XML Files

Raw XML files can be viewed in all major browsers.

Don't expect XML files to be displayed as HTML pages.

Viewing XML Files


<?xml version="1.0" encoding="ISO-8859-1"?>

- <note>

<to>Tove</to>

<from>Jani</from>

<heading>Reminder</heading>

<body>Don't forget me this weekend!</body>

</note>

The XML document will be displayed with color-coded root and child elements. A plus (+) or
minus sign (-) to the left of the elements can be clicked to expand or collapse the element
structure. To view the raw XML source (without the + and - signs), select "View Page Source" or
"View Source" from the browser menu.

Note: In Netscape, Opera, and Safari, only the element text will be displayed. To view the raw
XML, you must right click the page and select "View Source"

Viewing an Invalid XML File

If an erroneous XML file is opened, the browser will report the error.

Look at this XML file: note_error.xml

Why Does XML Display Like This?

XML documents do not carry information about how to display the data.

Since XML tags are "invented" by the author of the XML document, browsers do not know if a
tag like <table> describes an HTML table or a dining table.

Without any information about how to display the data, most browsers will just display the XML
document as it is.

In the next chapters, we will take a look at different solutions to the display problem, using CSS,
XSLT and JavaScript
Look at this XML file: note.xml

Displaying XML with CSS

With CSS (Cascading Style Sheets) you can add display information to an XML document.

Displaying your XML Files with CSS?

It is possible to use CSS to format an XML document.

Below is a fraction of the XML file. The second line links the XML file to the CSS file:

<?xml version="1.0" encoding="ISO-8859-1"?>


<?xml-stylesheet type="text/css" href="cd_catalog.css"?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
.
.
.
.
</CATALOG>

Displaying XML with XSLT

With XSLT you can transform an XML document into HTML.


Displaying XML with XSLT

XSLT is the recommended style sheet language of XML.

XSLT (eXtensible Stylesheet Language Transformations) is far more sophisticated than CSS.

One way to use XSLT is to transform XML into HTML before it is displayed by the browser as
demonstrated in these examples:

Below is a fraction of the XML file. The second line links the XML file to the XSLT file:

<?xml version="1.0" encoding="ISO-8859-1"?>


<?xml-stylesheet type="text/xsl" href="simple.xsl"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>
two of our famous Belgian Waffles
</description>
<calories>650</calories>
</food>
</breakfast_menu>

If you want to learn more about XSLT, find our XSLT tutorial on our homepage.

Transforming XML with XSLT on the Server

In the example above, the XSLT transformation is done by the browser, when the browser reads
the XML file.

Different browsers may produce different result when transforming XML with XSLT. To reduce
this problem the XSLT transformation can be done on the server.

Note that the result of the output is exactly the same, either the transformation is done by the web
server or by the web browser.

XML Parser

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

Load and parse an XML string

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
accessed 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 (elements) and their attributes.

Note: When we talk about parsing XML, we often use the term "Nodes" about XML elements.

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 ("note.xml") into the parser:

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");


xmlDoc.async="false";
xmlDoc.load("note.xml");

Example explained:

• The first line of the script above 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
"note.xml".

The following JavaScript fragment loads a string called txt into the parser:

var 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.

XML Parser in Firefox and Other Browsers

The following JavaScript fragment loads an XML document ("note.xml") into the parser:

var xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.async="false";
xmlDoc.load("note.xml");

Example explained:

• The first line of the script above creates an empty XML document
object.
• The second line turns off synchronized 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
"note.xml".

The following JavaScript fragment loads a string called txt into the parser:

var parser=new DOMParser();


var doc=parser.parseFromString(txt,"text/xml");

Example explained:

• The first line of the script above 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 DOM Parser object.

Access Across Domains

For security reasons, modern browsers do 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".

The XML DOM

In the next chapter of this tutorial, you will learn how to access and retrieve data from the XML
document object (the XML DOM).

XML DOM

The DOM (Document Object Model) defines a standard way for accessing and manipulating
documents.

The XML DOM

The DOM views XML documents as a tree-structure. All elements can be accessed through the
DOM tree. Their content (text and attributes) can be modified or deleted, and new elements can
be created. The elements, their text, and their attributes are all known as nodes.

In the examples below we use the following DOM reference to get the text from the <to>
element:

xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue

• xmlDoc - the XML document created by the parser.


• getElementsByTagName("to")[0] - the first <to> element
• childNodes[0] - the first child of the <to> element (the text node)
• nodeValue - the value of the node (the text itself)

The HTML DOM

The HTML DOM (HTML Document Object Model) defines a standard way for accessing and
manipulating HTML documents.

All HTML elements can be accessed through the HTML DOM.

In the examples below we use the following DOM reference to change the text of the HTML
element where id="to":

document.getElementById("to").innerHTML=

• document - the HTML document


• getElementById("to") - the HTML element where id="to"
• innerHTML - the inner text of the HTML element

Parsing an XML File - A Cross browser Example

The following code loads an XML document ("note.xml") into the XML parser:

<html>
<head>
<script type="text/javascript">
function parseXML()
{
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);
return;
}
}
xmlDoc.async=false;
xmlDoc.load("note.xml");
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}
</script>
</head>

<body onload="parseXML()">
<h1>W3Schools Internal Note</h1>
<p><b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span>
</p>
</body>
</html>

Output:

W3Schools Internal Note


To: Tove
From: Jani
Message: Don't forget me this weekend!

Important Note

To extract the text "Jani" from the XML, the syntax is:

getElementsByTagName("from")[0].childNodes[0].nodeValue

In the XML example there is only one <from> tag, but you still have to specify the array index
[0], because the XML parser method getElementsByTagName() returns an array of all <from>
nodes.

Parsing an XML String - A Cross browser Example

The following code loads and parses an XML string:

<html>
<head>
<script type="text/javascript">
function parseXML()
{
text="<note>";
text=text+"<to>Tove</to>";
text=text+"<from>Jani</from>";
text=text+"<heading>Reminder</heading>";
text=text+"<body>Don't forget me this weekend!</body>";
text=text+"</note>";
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);
return;
}
}
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}
</script>
</head>

<body onload="parseXML()">
<h1>W3Schools Internal Note</h1>
<p><b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span>
</p>
</body>
</html>

Output:
W3Schools Internal Note
To: Tove
From: Jani
Message: Don't forget me this weekend!

<html>

<head>

<script type="text/javascript">

function parseXML()

text="<note>";

text=text+"<to>Tove</to>";

text=text+"<from>Jani</from>";

text=text+"<heading>Reminder</heading>";

text=text+"<body>Don't forget me this weekend!</body>";

text=text+"</note>";

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

return;

document.getElementById("to").innerHTML=xmlDoc.getElementsByTagName("to")[0].childN
odes[0].nodeValue;

document.getElementById("from").innerHTML=xmlDoc.getElementsByTagName("from")[0].c
hildNodes[0].nodeValue;

document.getElementById("message").innerHTML=xmlDoc.getElementsByTagName("body")[
0].childNodes[0].nodeValue;

</script>

</head>

<body onload="parseXML()">

<h1>W3Schools Internal Note</h1>

<p><b>To:</b> <span id="to"></span><br />


<b>From:</b> <span id="from"></span><br />

<b>Message:</b> <span id="message"></span>

</p>

</body>

</html>

Display XML Data in HTML

In the last chapter, we explained how to parse XML and access the DOM with JavaScript.

In this example, we loop through an XML file (cd_catalog.xml), and display each CD element as
an HTML table row:

<html>
<body>

<script type="text/javascript">
var xmlDoc=null;
if (window.ActiveXObject)
{// code for IE
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
else if (document.implementation.createDocument)
{// code for Mozilla, Firefox, Opera, etc.
xmlDoc=document.implementation.createDocument("","",null);
}
else
{
alert('Your browser cannot handle this script');
}
if (xmlDoc!=null)
{
xmlDoc.async=false;
xmlDoc.load("cd_catalog.xml");

document.write("<table border='1'>");

var x=xmlDoc.getElementsByTagName("CD");
for (i=0;i<x.length;i++)
{
document.write("<tr>");
document.write("<td>");
document.write(
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue);
document.write("</td>");

document.write("<td>");
document.write(
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
document.write("</td>");
document.write("</tr>");
}
document.write("</table>");
}
</script>

</body>
</html>

Example explained

• We check the browser, and load the XML using the correct parser
• We create an HTML table with <table border="1">
• We use getElementsByTagName() to get all XML CD nodes
• For each CD node, we display data from ARTIST and TITLE as table
data.
• We end the table with </table>

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".

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 developer’s 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):

var xmlhttp = new XMLHttpRequest()

In Internet Explorer 5 and 6:

var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")

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

Is the XMLHttpRequest Object a W3C Standard?

The XMLHttpRequest object is not specified in any W3C recommendation.

However, the W3C DOM Level 3 "Load and Save" specification contains some similar
functionality, but these are not implemented in any browsers yet.
XML Application

The XML Example Document

Look at the following XML document ("cd_catalog.xml"), that represents a CD catalog:

<?xml version="1.0" encoding="ISO-8859-1"?>


<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
.
.
... more ...
.

Load the XML Document

To load the XML document (cd_catalog.xml), we use the same code as we used in the XML
Parser chapter:

var xmlDoc;
if (window.ActiveXObject)
{// code for IE
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
else if (document.implementation.createDocument)
{// code for Firefox, Mozilla, Opera, etc.
xmlDoc=document.implementation.createDocument("","",null);
}
else
{
alert('Your browser cannot handle this script');
}
xmlDoc.async=false;
xmlDoc.load("cd_catalog.xml");

After the execution of this code, xmlDoc is an XML DOM object, accessible by JavaScript.

Display XML Data as an HTML Table

The following code displays an HTML table filled with data from the XML DOM object:

document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("CD");
for (var i=0;i<x.length;i++)
{
document.write("<tr>");
document.write("<td>");
document.write(
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue);
document.write("</td>");

document.write("<td>");
document.write(
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
document.write("</td>");
document.write("</tr>");
}
document.write("</table>");

For each CD element in the XML document, a table row is created. Each table row contains two
table data cells with ARTIST and TITLE data from the current CD element.

Display XML Data in any HTML Element

XML data can be copied into any HTML element that can display text.

The code below is part of the <head> section of the HTML file. It gets the XML data from the
first <CD> element and displays it in the HTML element with the id="show":

var x=xmlDoc.getElementsByTagName("CD");
i=0;

function display()
{
artist=
(x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue);
title=
(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
year=
(x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue);
txt="Artist: "+artist+"<br />Title: "+title+"<br />Year: "+year;

document.getElementById("show").innerHTML=txt;
}

The body of the HTML document contains an onload eventattribute that will call the display()
function when the page has loaded. It also contains a <div id='show'> element to receive the
XML data.

<body onload="display()">
<div id='show'></div>
</body>

Add a Navigation Script

To add navigation to the example above, create two functions called next() and previous():

function next()
{
if (i<x.length-1)
{
i++;
display();
}
}

function previous()
{
if (i>0)
{
i--;
display();
}
}

The next() function makes sure that nothing is displayed if you already are at the last CD
element, and the previous () function makes sure that nothing is displayed if you already are at
the first CD element.
The next() and previous() functions are called by clicking next/previous buttons:

<input type="button" onclick="previous()" value="previous" />


<input type="button" onclick="next()" value="next" />

XML Namespaces

XML Namespaces provide a method to avoid element name conflicts.

Name Conflicts

In XML, element names are defined by the developer. This often results in a conflict when trying
to mix XML documents from different XML applications.

This XML carries HTML table information:

<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>

This XML carries information about a table (a piece of furniture):

<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>

If these XML fragments were added together, there would be a name conflict. Both contain a
<table> element, but the elements have different content and meaning.

An XML parser will not know how to handle these differences.

Solving the Name Conflict Using a Prefix

Name conflicts in XML can easily be avoided using a name prefix.

This XML carries information about an HTML table, and a piece of furniture:
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>

In the example above, there will be no conflict because the two <table> elements have different
names.

XML Namespaces - The xmlns Attribute

When using prefixes in XML, a so-called namespace for the prefix must be defined.

The namespace is defined by the xmlns attribute in the start tag of an element.

The namespace declaration has the following syntax. xmlns:prefix="URI".

<root>
<h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table xmlns:f="http://www.w3schools.com/furniture">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>

In the example above, the xmlns attribute in the <table> tag give the h: and f: prefixes a qualified
namespace.

When a namespace is defined for an element, all child elements with the same prefix are
associated with the same namespace.
Namespaces can be declared in the elements where they are used or in the XML root element:

<root
xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furniture">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>

Note: The namespace URI is not used by the parser to look up information.

The purpose is to give the namespace a unique name. However, often companies use the
namespace as a pointer to a web page containing namespace information.

Try to go to http://www.w3.org/TR/html4/.

Uniform Resource Identifier (URI)

A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet


Resource.

The most common URI is the Uniform Resource Locator (URL) which identifies an Internet
domain address. Another, not so common type of URI is the Universal Resource Name (URN).

In our examples we will only use URLs.

Default Namespaces

Defining a default namespace for an element saves us from using prefixes in all the child
elements. It has the following syntax:

xmlns="namespaceURI"
This XML carries HTML table information:

<table xmlns="http://www.w3.org/TR/html4/">
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>

This XML carries information about a piece of furniture:

<table xmlns="http://www.w3schools.com/furniture">
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>

Namespaces in Real Use

XSLT is an XML language that can be used to transform XML documents into other formats,
like HTML.

In the XSLT document below, you can see that most of the tags are HTML tags.

The tags that are not HTML tags have the prefix xsl, identified by the namespace
xmlns:xsl="http://www.w3.org/1999/XSL/Transform":

<?xml version="1.0" encoding="ISO-8859-1"?>


<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr>
<th align="left">Title</th>
<th align="left">Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

XML CDATA

All text in an XML document will be parsed by the parser.

But text inside a CDATA section will be ignored by the parser.

PCDATA - Parsed Character Data

XML parsers normally parse all the text in an XML document.

When an XML element is parsed, the text between the XML tags is also parsed:

<message>This text is also parsed</message>

The parser does this because XML elements can contain other elements, as in this example,
where the <name> element contains two other elements (first and last):

<name><first>Bill</first><last>Gates</last></name>

and the parser will break it up into sub-elements like this:

<name>
<first>Bill</first>
<last>Gates</last>
</name>

Parsed Character Data (PCDATA) is a term used about text data that will be parsed by the XML
parser.

CDATA - (Unparsed) Character Data

The term CDATA is used about text data that should not be parsed by the XML parser.

Characters like "<" and "&" are illegal in XML elements.


"<" will generate an error because the parser interprets it as the start of a new element.

"&" will generate an error because the parser interprets it as the start of an character entity.

Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script
code can be defined as CDATA.

Everything inside a CDATA section is ignored by the parser.

A CDATA section starts with "<![CDATA[" and ends with "]]>":

<script>
<![CDATA[
function matchwo(a,b)
{
if (a < b && a < 0) then
{
return 1;
}
else
{
return 0;
}
}
]]>
</script>

In the example above, everything inside the CDATA section is ignored by the parser.

Notes on CDATA sections:

A CDATA section cannot contain the string "]]>". Nested CDATA sections are not allowed.

The "]]>" that marks the end of the CDATA section cannot contain spaces or line breaks.

XML Encoding

XML documents can contain non ASCII characters, like Norwegian æ ø å , or French ê è é.

To avoid errors, specify the XML encoding, or save XML files as Unicode.

XML Encoding Errors

If you load an XML document, you can get two different errors indicating encoding problems:
An invalid character was found in text content.

You get this error if your XML contains non ASCII characters, and the file was saved as single-
byte ANSI (or ASCII) with no encoding specified.

Switch from current encoding to specified encoding not supported.

You get this error if your XML file was saved as double-byte Unicode (or UTF-16) with a single-
byte encoding (Windows-1252, ISO-8859-1, UTF-8) specified.

You also get this error if your XML file was saved with single-byte ANSI (or ASCII), with
double-byte encoding (UTF-16) specified.

Windows Notepad

Windows Notepad saves files as single-byte ANSI (ASCII) by default.

If you select "Save as...", you can specify double-byte Unicode (UTF-16).

Save the XML file below as Unicode (note that the document does not contain any encoding
attribute):

<?xml version="1.0"?>
<note>
<from>Jani</from>
<to>Tove</to>
<message>Norwegian: æøå. French: êèé</message>
</note>

The file above, note_encode_none_u.xml will NOT generate an error. But if you specify a single-
byte encoding it will.

The following encoding (open it), will give an error message:

<?xml version="1.0" encoding="windows-1252"?>

The following encoding (open it), will give an error message:

<?xml version="1.0" encoding="ISO-8859-1"?>

The following encoding (open it), will give an error message:

<?xml version="1.0" encoding="UTF-8"?>

The following encoding (open it), will NOT give an error:


<?xml version="1.0" encoding="UTF-16"?>

Conclusion

• Always use the encoding attribute


• Use an editor that supports encoding
• Make sure you know what encoding the editor uses
• Use the same encoding in your encoding attribute

XML on the Server

XML files are plain text files just like HTML files.

XML can easily be stored and generated by a standard web server.

Storing XML Files on the Server

XML files can be stored on an Internet server exactly the same way as HTML files.

Start Windows Notepad and write the following lines:

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<from>Jani</from>
<to>Tove</to>
<message>Remember me this weekend</message>
</note>

Save the file on your web server with a proper name like "note.xml".

Generating XML with ASP

XML can be generated on a server without any installed XML software.

To generate an XML response from the server - simply write the following code and save it as an
ASP file on the web server:

<%
response.ContentType="text/xml"
response.Write("<?xml version='1.0' encoding='ISO-8859-1'?>")
response.Write("<note>")
response.Write("<from>Jani</from>")
response.Write("<to>Tove</to>")
response.Write("<message>Remember me this weekend</message>")
response.Write("</note>")
%>

Note that the content type of the response must be set to "text/xml".

Generating XML with PHP

To generate an XML response from the server using PHP, use following code:

<?php
header("Content-type: text/xml");
echo "<?xml version='1.0' encoding='ISO-8859-1'?>";
echo "<note>";
echo "<from>Jani</from>";
echo "<to>Tove</to>";
echo "<message>Remember me this weekend</message>";
echo "</note>";
?>

Note that the content type of the response header must be set to "text/xml".

See how the PHP file will be returned from the server.

If you want to study PHP, you will find our PHP tutorial on our homepage.

Generating XML From a Database

XML can be generated from a database without any installed XML software.

To generate an XML database response from the server, simply write the following code and
save it as an ASP file on the web server:

<%
response.ContentType = "text/xml"
set conn=Server.CreateObject("ADODB.Connection")
conn.provider="Microsoft.Jet.OLEDB.4.0;"
conn.open server.mappath("/db/database.mdb")
sql="select fname,lname from tblGuestBook"
set rs=Conn.Execute(sql)
response.write("<?xml version='1.0' encoding='ISO-8859-1'?>")
response.write("<guestbook>")
while (not rs.EOF)
response.write("<guest>")
response.write("<fname>" & rs("fname") & "</fname>")
response.write("<lname>" & rs("lname") & "</lname>")
response.write("</guest>")
rs.MoveNext()
wend
rs.close()
conn.close()
response.write("</guestbook>")
%>

See the real life database output from the ASP file above.

The example above uses ASP with ADO.

If you want to study ASP and ADO, you will find the tutorials on our homepage.

Transforming XML with XSLT on the Server

This ASP transforms an XML file to XHTML on the server:

<%
'Load XML
set xml = Server.CreateObject("Microsoft.XMLDOM")
xml.async = false
xml.load(Server.MapPath("simple.xml"))

'Load XSL
set xsl = Server.CreateObject("Microsoft.XMLDOM")
xsl.async = false
xsl.load(Server.MapPath("simple.xsl"))

'Transform file
Response.Write(xml.transformNode(xsl))
%>

Example explained

• The first block of code creates an instance of the Microsoft XML parser
(XMLDOM), and loads the XML file into memory.
• The second block of code creates another instance of the parser and
loads the XSL file into memory.
• The last line of code transforms the XML document using the XSL
document, and sends the result as XHTML to your browser. Nice!

Saving XML To a File Using ASP

This ASP example creates a simple XML document and saves it on the server:

<%
text="<note>"
text=text & "<to>Tove</to>"
text=text & "<from>Jani</from>"
text=text & "<heading>Reminder</heading>"
text=text & "<body>Don't forget me this weekend!</body>"
text=text & "</note>"

set xmlDoc=Server.CreateObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.loadXML(text)
xmlDoc.Save("test.xml")
%>

XML DOM Advanced

The XML DOM (Document Object Model) defines a standard way for accessing and
manipulating XML documents.

The XML DOM

The DOM views XML documents as a tree-structure. All elements can be accessed through the
DOM tree. Their content (text and attributes) can be modified or deleted, and new elements can
be created. The elements, their text, and their attributes are all known as nodes.

In an earlier chapter of this tutorial we introduced the XML DOM , and used the XML DOM
getElementsByTagName() method to retrieve data from a DOM tree.

In this chapter we will describe some other commonly used XML DOM methods. In the
examples, we have used the XML file books.xml, and a JavaScript function to load the XML file
into an DOM object called xmlDoc.

To learn all about the XML DOM, please visit our XML DOM tutorial.
Get the Value of an Element

The following code retrieves the text value of the first <title> element:

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

Result: txt = "Everyday Italian"

Get the Value of an Attribute

The following code retrieves the text value of the "lang" attribute of the first <title> element:

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

Result: txt = "en"

Change the Value of an Element

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

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

Change the Value of an Attribute

The setAttribute() method can be used to change the value of an existing attribute, or to create a
new attribute.

The following code adds a new attribute called "edition" (with the value "first") to each <book>
element:

x=xmlDoc.getElementsByTagName("book");
for(i=0;i<x.length;i++)
{
x[i].setAttribute("edition","first");
}

Create an Element
The createElement() method creates a new element node.

The createTextNode() method creates a new text node.

The appendChild() method adds a child node to a node (after the last child).

To create a new element with text content, it is necessary to create both an element node and a
text node.

The following code creates an element (<edition>), and adds it to the first <book> element:

newel=xmlDoc.createElement("edition");
newtext=xmlDoc.createTextNode("First");
newel.appendChild(newtext);
x=xmlDoc.getElementsByTagName("book");
x[0].appendChild(newel);

Example explained:

• Create an <edition> element


• Create a text node with value = "First"
• Append the text node to the <edition> element
• Append the <edition> element to the first <book> element

Remove an Element

The removeChild() method removes a specified node (or element).

The following code fragment will remove the first node in the first <book> element:

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

Note: The result of the example above may be different depending on what browser you use.
Firefox treats new lines as empty text nodes, Internet Explorer don't. You can read more about
this and how to avoid it in the XML DOM tutorial.

XML Don't

Here are some technologies you should try to avoid when using XML.
Internet Explorer - XML Data Islands

What is it? An XML data island is XML data embedded into an HTML page.

Why avoid it? XML Data Islands only works with Internet Explorer browsers.

What to use instead? You should use JavaScript and XML DOM to parse and display XML in
HTML.

XML Data Island Example

This example uses the XML document "cd_catalog.xml".

Bind the XML document to an <xml> tag in the HTML document. The id attribute defines an id
for the data island, and the src attribute points to the XML file:

<html>
<body>

<xml id="cdcat" src="cd_catalog.xml"></xml>

<table border="1" datasrc="#cdcat">


<tr>
<td><span datafld="ARTIST"></span></td>
<td><span datafld="TITLE"></span></td>
</tr>
</table>

</body>
</html>

The datasrc attribute of the <table> tag binds the HTML table to the XML data island.

The <span> tags allow the datafld attribute to refer to the XML element to be displayed. In this
case, "ARTIST" and "TITLE". As the XML is read, additional rows are created for each <CD>
element.

Internet Explorer - Behaviors


What is it? Internet Explorer 5 introduced behaviors. Behaviors are a way to add behaviors to
XML (or HTML) elements with the use of CSS styles.

Why avoid it? The behavior attribute is only supported by Internet Explorer.

What to use instead? Use JavaScript and XML DOM (or HTML DOM) instead.

Example 1 - Mouseover Highlight

The following HTML file has a <style> element that defines a behavior for the <h1> element:

<html>
<head>
<style type="text/css">
h1 { behavior: url(behave.htc) }
</style>
</head>

<body>
<h1>Mouse over me!!!</h1>
</body>
</html>

The XML document "behave.htc" is shown below:

<attach for="element" event="onmouseover" handler="hig_lite" />


<attach for="element" event="onmouseout" handler="low_lite" />

<script type="text/javascript">
function hig_lite()
{
element.style.color='red';
}
function low_lite()
{
element.style.color='blue';
}
</script>

The behavior file contains a JavaScript and event handlers for the elements.

Example 2 - Typewriter Simulation

The following HTML file has a <style> element that defines a behavior for elements with an id
of "typing":
<html>
<head>
<style type="text/css">
#typing
{
behavior:url(typing.htc);
font-family:'courier new';
}
</style>
</head>

<body>
<span id="typing" speed="100">IE5 introduced DHTML behaviors.
Behaviors are a way to add DHTML functionality to HTML elements
with the ease of CSS.<br /><br />How do behaviors work?<br />
By using XML we can link behaviors to any element in a web page
and manipulate that element.</p>
</span>
</body>
</html>

The XML document "typing.htc" is shown below:

<attach for="window" event="onload" handler="beginTyping" />


<method name="type" />
<script type="text/javascript">
var i,text1,text2,textLength,t;
function beginTyping()
{
i=0;
text1=element.innerText;
textLength=text1.length;
element.innerText="";
text2="";
t=window.setInterval(element.id+".type()",speed);
}
function type()
{
text2=text2+text1.substring(i,i+1);
element.innerText=text2;
i=i+1;
if (i==textLength)
{
clearInterval(t);
}
}
</script>
<html>

<head>

<style type="text/css">

#typing

behavior:url(typing.htc);

font-family:'courier new';

</style>

</head>

<body>

<span id="typing" speed="100">IE5 introduced DHTML behaviors. Behaviors are a way to add
DHTML functionality to HTML elements with the ease of CSS.<br /><br />How does behaviors
work?<br />By using XML we can link behaviors to any element in a web page and manipulate
that element.</p>

</span>

</body>

</html>

XML Related Technologies

Below is a list of XML technologies.


XHTML (Extensible HTML)
A stricter and cleaner XML based version of HTML.

XML DOM (XML Document Object Model)


A standard document model for accessing and manipulating XML.

XSL (Extensible Style Sheet Language) XSL consists of three parts:

• XSLT (XSL Transform) - transforms XML into other formats, like HTML
• XSL-FO (XSL Formatting Objects)- for formatting XML to screen, paper,
etc
• XPath - a language for navigating XML documents

XQuery (XML Query Language)


An XML based language for querying XML data.

DTD (Document Type Definition)


A standard for defining the legal elements in an XML document.

XSD (XML Schema)


An XML-based alternative to DTD.

XLink (XML Linking Language)


A language for creating hyperlinks in XML documents.

XPointer (XML Pointer Language)


Allows the XLink hyperlinks to point to more specific parts in the XML document.

XForms (XML Forms)


Uses XML to define form data.

SOAP (Simple Object Access Protocol)


An XML-based protocol to let applications exchange information over HTTP.

WSDL (Web Services Description Language)


An XML-based language for describing web services.

RDF (Resource Description Framework)


An XML-based language for describing web resources.

RSS (Really Simple Syndication)


A format for syndicating news and the content of news-like sites.

WAP (Wireless Application Protocol)


A XML based language for displaying content on wireless clients, like mobile phones.
SMIL (Synchronized Multimedia Integration Language)
A language for describing audiovisual presentations.

SVG (Scalable Vector Graphics)


Defines graphics in XML format.

XML in Real Life

Some examples of how XML can be used to exchange information.

Example: XML News

XMLNews is a specification for exchanging news and other information.

Using such a standard makes it easier for both news producers and news consumers to produce,
receive, and archive any kind of news information across different hardware, software, and
programming languages.

An example XMLNews document:

<?xml version="1.0" encoding="ISO-8859-1"?>

<nitf>

<head>
<title>Colombia Earthquake</title>
</head>

<body>

<headline>
<hl1>143 Dead in Colombia Earthquake</hl1>
</headline>
<byline>
<bytag>By Jared Kotler, Associated Press Writer</bytag>
</byline>
<dateline>
<location>Bogota, Colombia</location>
<date>Monday January 25 1999 7:28 ET</date>
</dateline>

</body>
</nitf>

Example: XML Weather Service

An example of an XML national weather service from NOAA (National Oceanic and
Atmospheric Administration):

<?xml version="1.0" encoding="ISO-8859-1" ?>


<current_observation>
<credit>NOAA's National Weather Service</credit>
<credit_URL>http://weather.gov/</credit_URL>
<image>
<url>http://weather.gov/images/xml_logo.gif</url>
<title>NOAA's National Weather Service</title>
<link>http://weather.gov</link>
</image>
<location>New York/John F. Kennedy Intl Airport, NY</location>
<station_id>KJFK</station_id>
<latitude>40.66</latitude>
<longitude>-73.78</longitude>
<observation_time_rfc822>
Mon, 11 Feb 2008 06:51:00 -0500 EST
</observation_time_rfc822>
<weather>A Few Clouds</weather>
<temp_f>11</temp_f>
<temp_c>-12</temp_c>
<relative_humidity>36</relative_humidity>
<wind_dir>West</wind_dir>
<wind_degrees>280</wind_degrees>
<wind_mph>18.4</wind_mph>
<wind_gust_mph>29</wind_gust_mph>
<pressure_mb>1023.6</pressure_mb>
<pressure_in>30.23</pressure_in>
<dewpoint_f>-11</dewpoint_f>
<dewpoint_c>-24</dewpoint_c>
<windchill_f>-7</windchill_f>
<windchill_c>-22</windchill_c>
<visibility_mi>10.00</visibility_mi>
<icon_url_base>
http://weather.gov/weather/images/fcicons/
</icon_url_base>
<icon_url_name>nfew.jpg</icon_url_name>
<two_day_history_url>
http://www.weather.gov/data/obhistory/KJFK.html
</two_day_history_url>
<disclaimer_url>
http://weather.gov/disclaimer.html
</disclaimer_url>
<copyright_url>
http://weather.gov/disclaimer.html
</copyright_url>
</current_observation>

XML DOM

XML DOM Tutorial


XML DOM Tutorial

The XML DOM (Document Object Model) defines a standard way for accessing and
manipulating XML documents.

The DOM presents an XML document as a tree structure, with elements, attributes, and text as
nodes:

Knowing the XML DOM is a must for anyone working with XML.
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

If you want to study these subjects first, find the tutorials on our Home page.

What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents like XML and HTML:

"The W3C Document Object Model (DOM) is a platform and language-neutral interface that
allows programs and scripts to dynamically access and update the content, structure, and style
of a document."

The DOM is separated into 3 different parts / levels:

• Core DOM - standard model for any structured document


• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents

The DOM defines the objects and properties of all document elements, and the methods
(interface) to access them.

What is the HTML DOM?

The HTML DOM defines the objects and properties of all HTML elements, and the methods
(interface) to access them.

If you want to study the HTML DOM, find the HTML DOM tutorial on our homepage.

What is the XML DOM?


The XML DOM is:

• A standard object model for XML


• A standard programming interface for XML
• Platform- and language-independent
• A W3C standard

The XML DOM defines the objects and properties of all XML elements, and the methods
(interface) to access them.

In other words:

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

XML DOM Nodes

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

DOM Nodes

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

The DOM says:

• The entire document is a document node


• Every XML element is an element node
• The text in the XML elements are text nodes
• Every attribute is an attribute node
• Comments are comment nodes

DOM Example

Look at the following XML file (books.xml):

<?xml version="1.0" encoding="ISO-8859-1"?>


<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

The root node in the XML above is named <bookstore>. All other nodes in the document are
contained within <bookstore>.

The root node <bookstore> holds four <book> nodes.

The first <book> node holds four nodes: <title>, <author>, <year>, and <price>, which contains
one text node each, "Everyday Italian", "Giada De Laurentiis", "2005", and "30.00".

Text is Always Stored in Text Nodes

A common error in DOM processing is to expect an element node to contain text.

However, the text of an element node is stored in a text node.

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

XML DOM Node Tree

The XML DOM views an XML document as a node-tree.

All the nodes in the tree have a relationship to each other.

The XML DOM Node Tree

The XML DOM views an XML document as a tree-structure. The tree structure is called a node-
tree.

All nodes can be accessed through the tree. Their contents can be modified or deleted, and new
elements can be created.

The node tree shows the set of nodes, and the connections between them. The tree starts at the
root node and branches out to the text

nodes at the lowest level of the tree:

The image above represents the XML file books.xml.


Node Parents, Children, and Siblings

The nodes in the node tree have a hierarchical relationship to each other.

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

• In a node tree, the top node is called the root


• Every node, except the root, has exactly one parent node
• A node can have any number of children
• A leaf is a node with no children
• Siblings are nodes with the same parent

The following image illustrates a part of the node tree and the relationship between the nodes:

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

You will learn more about traversing the node tree in a later chapter of this tutorial.

First Child - Last Child

Look at the following XML fragment:


<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>

In the XML above, the <title> element is the first child of the <book> element, and the <price>
element is the last child of the <book> element.

Furthermore, the <book> element is the parent node of the <title>, <author>, <year>, and
<price> elements.

Parsing the XML DOM

Most browsers have a build-in XML parser to read and manipulate XML.

The parser converts XML into a JavaScript accessible object.

Examples

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

Load and parse an XML file

Load and parse an XML string

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.

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:

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

Try it yourself

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:

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

try //Internet Explorer


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

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:

function 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);
}

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

Try it yourself

An External Load Function

To make the function above even easier to maintain, and to make sure the same code is used in
all pages, it can be stored in an external file.

We have called the file "loadxmldoc.js"

The file can be loaded in the <head> section of an HTML page, and loadXMLDoc() can be
called from a script in the page:

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

<body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
document.write("xmlDoc is loaded, ready for use");
</script>
</body>
</html>

Try it yourself

The function described above, is used in all examples in this tutorial


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


Load and parse an XML string

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

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

XML DOM Methods

• x.getElementsByTagName(name) - get all elements with a specified


tag name
• x.appendChild(node) - insert a child node to x
• x.removeChild(node) - remove a child node from x

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

Example

The JavaScript code to get the text from the first <title> element in books.xml:

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

After the execution of the statement, txt will hold the value "Everyday Italian"
Explained:

• xmlDoc - the XML DOM object created by the parser.


• getElementsByTagName("title")[0] - the first <title> element
• childNodes[0] - the first child of the <title> element (the text node)
• nodeValue - the value of the node (the text itself)

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


are properties.

Parsing an XML File - A Cross browser Example

The following code fragment uses the loadXMLDoc function (described in the previous chapter)
to load books.xml into the XML parser, and displays data from the first book:

xmlDoc=loadXMLDoc("books.xml");
document.write(xmlDoc.getElementsByTagName("title")
[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("author")
[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("year")
[0].childNodes[0].nodeValue);

Output:

Everyday Italian
Giada De Laurentiis
2005

Try it yourself

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:
text="<bookstore>"
text=text+"<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
text=text+"</bookstore>";

xmlDoc=loadXMLString(text);

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

Output:

Everyday Italian
Giada De Laurentiis
2005

XML DOM - Accessing Nodes

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

Examples

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Access a node using its index number in a node list


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

<html>

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

</head>

<body>

<script type="text/javascript">

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title");

document.write(x[2].childNodes[0].nodeValue);

</script>

</body>

</html>

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>

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>

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>

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>

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

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.

Syntax
node.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:

y=x[2];

Try it yourself.

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:

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

Example explained:

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


2. Get all <title> element nodes
3. For each title element, output the value of its text node

Try it yourself.
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.

Try it yourself.

Traversing Nodes

The following code loops through the child nodes, that are also element nodes, of the root node:

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

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

Try it yourself.

Navigating Node Relationships

The following code navigates the node tree using the node relationships:

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;
}

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


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

XML DOM Node Information

The node properties: nodeName, nodeValue, and nodeType.

Examples

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>

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>

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>

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

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>

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

Try it yourself.

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:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
txt=x.nodeValue;

Result: txt = "Everyday Italian"

Example explained:

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


2. Get text node of the first <title> element node
3. Set the txt variable to be the value of the text node

Try it yourself

Example 2: Change the Value of an Element

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

xmlDoc=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 text node of the first <title> element node
3. Change the value of the text node to "Easy Cooking"

Try it yourself

The nodeType Property

The nodeType property specifies the type of node.

nodeType is read only.

The most important node types are:

Node type NodeType

Element 1

Attribute 2
Text 3

Comment 8

Document 9

XML DOM Node List

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

Examples

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Get the text from the first <title> element


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

<html>

<head>

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

</script>

</head>

<body>

<script type="text/javascript">

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title");

txt=x[0].childNodes[0].nodeValue;

document.write(txt);

</script>

</body>

</html>

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"

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

Get the attribute of an element


This example uses a attribute list to get attribute from the first <book> element in "books.xml".

<html>

<head>

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

</script>

</head>

<body>

<script type="text/javascript">

xmlDoc=loadXMLDoc("books.xml");

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

document.write(x.getNamedItem("category").nodeValue);

document.write("<br />" + x.length);

</script>

</body>

</html>
DOM Node List

When using properties or methods like childNodes or getElementsByTagName(), a node list


object is returned.

A node list object represents a list of nodes, in the same order as in the XML.

Nodes in the node list are accessed with index numbers starting from 0.

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

The following code fragment loads "books.xml" into xmlDoc using loadXMLDoc() and returns a
node list of title elements in "books.xml":

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title");

After the execution of the statement above, x is a node list object.

The following code fragment returns the text from the first <title> element in the node list (x):
txt=x[0].childNodes[0].nodeValue;

After the execution of the statement above, txt = "Everyday Italian".

Try it yourself.

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:

xmlDoc=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
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

Try it yourself.

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:

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

Output:

cooking
1

Example explained:

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


2. Set the x variable to hold a list of all attributes of the first <book>
element
3. Output the value from the "category" attribute
4. Output the length of the attribute list
XML DOM Traverse Node Tree

Traversing means looping through or traveling across the node tree.

Examples

The examples below use the XML file books.xml.


A function, loadXMLString(), in an external JavaScript is used to load the XML string.

Traverse a node tree


Loop through all child nodes of the <book> element

<html>

<head>

<script type="text/javascript" src="loadxmlstring.js"></script>

</head>

<body>

<script type="text/javascript">

text="<book>";

text=text+"<title>Everyday Italian</title>";

text=text+"<author>Giada De Laurentiis</author>";

text=text+"<year>2005</year>";

text=text+"</book>";

xmlDoc=loadXMLString(text);
// documentElement always represents the root node

x=xmlDoc.documentElement.childNodes;

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

document.write(x[i].nodeName);

document.write(": ");

document.write(x[i].childNodes[0].nodeValue);

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

</script>

</body>

</html>

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:

<html>
<head>
<script type="text/javascript" src="loadxmlstring.js"></script>
</head>
<body>
<script type="text/javascript">
text="<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
xmlDoc=loadXMLString(text);

// documentElement always represents the root node


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

Output:

title: Everyday Italian


author: Giada De Laurentiis
year: 2005

Example explained:

1. loadXMLString() loads the XML string into xmlDoc


2. Get the child nodes of the root element
3. For each child node, output the node name and the node value of the
text node

XML DOM Browser Differences

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

Examples

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Display the length of a node list


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

<head>

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

</head>

<body>

<script type="text/javascript">

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.documentElement.childNodes;

document.write("Number of child nodes: " + x.length);

</script>

</body>

</html>

Ignore empty text between nodes


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

<html>

<head>

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

</head>

<body>

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

x=xmlDoc.documentElement.childNodes;

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

if (x[i].nodeType==1)

document.write(x[i].nodeName);

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

</script>

</body>

</html>

Browser Differences in DOM Parsing

All modern browsers support the W3C DOM specification.

However, there are some differences between browsers. Two important differences are:

• The way they load XML


• The way they handle white-spaces and new lines

The different ways to load XML is explained in the chapter "DOM Parser".

The different ways to handle white spaces and new lines is explained in this chapter.

DOM - White Spaces and New Lines


XML often contains new line, or white space characters, between nodes. This is often the case
when the document is edited by a simple editor like Notepad.

The following example (edited by Notepad) contains CR/LF (new line) between each line and
two spaces in front of each child node:

<book>
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>

Firefox, and some other browsers, will treat empty white-spaces or new lines as text nodes,
Internet Explorer will not

The following code fragment displays how many child nodes the root element (of books.xml)
has:

xmlDoc=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.

Try it yourself

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:

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{
if (x[i].nodeType==1)
{// only process element nodes
document.write(x[i].nodeName);
document.write("<br />");
}
}

Example explained:

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


2. Get the child nodes of the root element
3. For each child node, check the node type of the node. If the node type
is "1" it is an element node
4. Output the name of the node if it is an element node

XML DOM - Navigating Nodes

Nodes can be navigated using node relationships.

Examples

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Get the parent of a node


This example uses the parentNode property to get the parent of a node

<html>

<head>

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

</script>

</head>

<body>

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

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

document.write(x.parentNode.nodeName);

</script>

</body>

</html>

Get the first child element of a node


This example uses the firstChild() method and a custom function to get the first child node of a
node

<html>

<head>

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

</script>

<script type="text/javascript">

//check if the first node is an element node

function get_firstChild(n)

y=n.firstChild;

while (y.nodeType!=1)

y=y.nextSibling;

}
return y;

</script>

</head>

<body>

<script type="text/javascript">

xmlDoc=loadXMLDoc("books.xml");

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

document.write(x.nodeName);

</script>

</body>

</html>

Navigating DOM Nodes

Accessing nodes in the node tree via the relationship between nodes, is often called "navigating
nodes".

In the XML DOM, node relationships are defined as properties to the nodes:

• parentNode
• childNodes
• firstChild
• lastChild
• nextSibling
• previousSibling
The following image illustrates a part of the node tree and the relationship between nodes in
books.xml:

DOM - Parent Node

All nodes has exactly one parent node. The following code navigates to the parent node of
<book>:

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0];
document.write(x.parentNode.nodeName);

Example explained:

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


2. Get the first <book> element
3. Output the node name of the parent node of "x"

Try it yourself

Avoid Empty Text Nodes


Firefox, and some other browsers, will treat empty white-spaces or new lines as text nodes,
Internet Explorer will not.

This causes a problem when using the properties: firstChild, lastChild, nextSibling,
previousSibling.

To avoid navigating to empty text nodes (spaces and new-line characters between element
nodes), we use a function that checks the node type:

function get_nextSibling(n)
{
y=n.nextSibling;
while (y.nodeType!=1)
{
y=y.nextSibling;
}
return y;
}

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

Code explained:

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

Get the First Child Element

The following code displays the first element node of the first <book>:

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

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

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

Output:

title

Example explained:

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


2. Use the get_firstChild fucntion on the first <book> element node to
get the first child node that is an element node
3. Output the node name of first child node that is an element node

XML DOM Get Node Values

The nodeValue property is used to get the text value of a node.

The getAttribute() method returns the value of an attribute.

Examples

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Get an element's value


This example uses the getElementsByTagname() method to get the first <title> element in
"books.xml"
Get an attribute's value
This example uses the getAttribute() method to get the value of the "category" attribute of the
first <title> element in "books.xml".

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:

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

Result: txt = "Everyday Italian"

Try it yourself

Loop through all <title> elements: Try it yourself


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.

The following code retrieves the text value of the "lang" attribute of the first <title> element:

xmlDoc=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

Try it yourself

Loop through all <book> elements and get their "category" attributes: Try it yourself

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:

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].getAttributeNode("lang"
);
txt=x.nodeValue;

Result: txt = "en"


Example explained:

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


2. Get the "lang" attribute node of the first <title> element node
3. Set the txt variable to be the value of the attribute

XML DOM Change Node Values

The nodeValue property is used to change a node value.

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

Examples

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Change an elements text node


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

Change an attributes value using setAttribute


This example uses the setAttribute() method to change the value of the "category" attribute of the
first <book>.

Change an attributes value using nodeValue


This example use the nodeValue property to change the value of the "category" attribute of the
first <book>.

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:

xmlDoc=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"

Try it yourself

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

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:

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

Example explained:

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


2. Get the first <book> element
3. Change the "category" attribute value to "food"
Try it yourself

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

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:

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

Example explained:

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


2. Get the "category" attribute of the first <book> element
3. Change the attribute node value to "food"

XML DOM Remove Nodes

The removeChild() method removes a specified node.

The removeAttribute() method removes a specified attribute.

Examples

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Remove an element node


This example uses removeChild() to remove the first <book> element.

Remove the current element node


This example uses parentNode and removeChild() to remove the current <book> element.
Remove a text node
This example uses removeChild() to remove the text node from the first <title> element.

Clear the text of a text node


This example uses the nodeValue() property to clear the text node of the first <title> element.

Remove an attribute by name


This example uses removeAttribute() to remove the "category" attribute from the first <book>
element.

Remove attributes by object


This example uses removeAttributeNode() to remove all attributes from all <book> elements.

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:

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

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

Try it yourself

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:

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0];
x.parentNode.removeChild(x);

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

Try it yourself

Remove a Text Node

The removeChild() method can also be used to remove a text node:

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0];

y=x.childNodes[0];
x.removeChild(y);

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

Try it yourself

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:

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

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

Try it yourself

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

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:

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book");
x[0].removeAttribute("category");

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

Try it yourself

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

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:

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

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
4. While there are attributes in a book element, remove the attribute

XML DOM Replace Nodes

The replaceChild() method replaces a specified node.

The nodeValue property replaces text in a text node.

Examples

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Replace an element node


This example uses replaceChild() to replace the first <book> node.

Replace data in a text node


This example uses the nodeValue property to replace data 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:


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

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

Try it yourself

Replace Data In a Text Node

The replaceData() method is used to replace data in a text node.

The replaceData() method has three parameters:

• offset - Where to begin replacing characters. Offset value starts at zero


• length - How many characters to replace
• string - The string to insert

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

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"

Try it yourself

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":

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

Example explained:

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


2. Get the text node of the first <title> element node
3. Use the nodeValue property to change the text of the text node

XML DOM Create Nodes

Examples

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Create an element node


This example uses createElement() to create a new element node, and appendChild() to add it to
a node.

Create an attribute node using createAttribute


This example uses createAttribute() to create a new attribute node, and setAttributeNode() to
insert it to an element.
Create an attribute node using setAttribute
This example uses setAttribute() to create a new attribute for an element.

Create a text node


This example uses createTextNode() to create a new text node, and appendChild() to add it to an
element.

Create a CDATA section node


This example uses createCDATAsection() to create a CDATA section node, and appendChild() to
add it to an element.

Create a comment node


This example uses createComment() to create a comment node, and appendChild() to add it to an
element.

Create a New Element Node

The createElement() method creates a new element node:

xmlDoc=loadXMLDoc("books.xml");

newel=xmlDoc.createElement("edition");

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

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

Try it yourself

Loop through and add an element to all <book> elements: Try it yourself

Create a New Attribute Node

The createAttribute() is used to create a new attribute node:

xmlDoc=loadXMLDoc("books.xml");
newatt=xmlDoc.createAttribute("edition");
newatt.nodeValue="first";
x=xmlDoc.getElementsByTagName("title");
x[0].setAttributeNode(newatt);

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

Try it yourself

Loop through all <title> elements and add a new attribute node: Try it yourself

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.

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

Try it yourself

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

Create a Text Node

The createTextNode() method creates a new text node:

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

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

Try it yourself

Add an element node, with a text node, to all <book> elements: Try it yourself

Create a CDATA Section Node

The createCDATASection() method creates a new CDATA section node.

xmlDoc=loadXMLDoc("books.xml");
newCDATA=xmlDoc.createCDATASection("Special Offer & Book Sale");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newCDATA);

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

Try it yourself

Loop through, and add a CDATA section, to all <book> elements: Try it yourself

Create a Comment Node

The createComment() method creates a new comment node.

xmlDoc=loadXMLDoc("books.xml");
newComment=xmlDoc.createComment("Revised March 2008");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newComment);
Example explained:

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


2. Create a new comment node
3. Append the new comment node to the first <book> element

XML DOM Add Nodes

Examples

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Add a node after the last child node


This example uses appendChild() to add a child node to an existing node.

Add a node before a specified child node


This example uses insertBefore() to insert a node before a specified child node.

Add a new attribute


This example uses the setAttribute() method to add a new attribute.

Add data to a text node


This example uses insertData() to insert data into an existing text node.

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:

xmlDoc=loadXMLDoc("books.xml");

newel=xmlDoc.createElement("edition");

x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);
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

Try it yourself

Loop through and append an element to all <book> elements: Try it yourself

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:

xmlDoc=loadXMLDoc("books.xml");
newNode=xmlDoc.createElement("book");
x=xmlDoc.documentElement;
y=xmlDoc.getElementsByTagName("book")[3];
x.insertBefore(newNode,y);

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

Try it yourself

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:

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

Try it yourself

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:

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

XML DOM Clone Nodes

Examples

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Copy a node and append it to an existing node


This example uses cloneNode() to copy a node and append it to the root node of the XML
document
Copy a Node

The cloneNode() method creates a copy of a specified node.

The cloneNode() method has a parameter (true or false). This parameter indicates if the cloned
node should include all attributes and child nodes of the original node.

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

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

//Output all titles


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

Output:

Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML
Everyday Italian

Example explained:

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


2. Get the node to copy
3. Copy the node into "newNode" using the cloneNode method
4. Append the new node to the the root node of the XML document
5. Output all titles for all books in the document

The XMLHttpRequest Object


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

What is the XMLHttpRequest Object?

The XMLHttpRequest object is the developers dream, because you can:

• Update a web page with new data without reloading the page
• Request data from a server after the page has loaded
• Receive data from a server after the page has loaded
• Send data to a server in the background

The XMLHttpRequest object is supported in all modern browsers.

Example: XML HTTP communication with a server while typing input

Creating an XMLHttpRequest Object

Creating an XMLHttpRequest object is done with one single line of JavaScript.

In all modern browsers (including IE7):

xmlhttp=new XMLHttpRequest()

In Internet Explorer 5 and 6:

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")

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

Try it yourself using JavaScript

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.

Try it yourself using JavaScript

More Examples

Load a textfile into a div element with XML HTTP

Make a HEAD request with XML HTTP

Make a specified HEAD request with XML HTTP

List data from an XML file with XML HTTP

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.

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

The ASP page, written in VBScript:

<%
set xmldoc = Server.CreateObject("Microsoft.XMLDOM")
xmldoc.async=false
xmldoc.load(request)

for each x in xmldoc.documentElement.childNodes


if x.NodeName = "to" then name=x.text
next
response.write(name)
%>

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

Try it yourself

Is the XMLHttpRequest Object a W3C Standard?

The XMLHttpRequest object is not specified in any W3C recommendation.

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

XML DOM Node Types

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

Examples

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.
Display nodeName and nodeType of all elements

Display nodeName and nodeValue of all elements

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 Element (max. one),


document (the root-node of ProcessingInstruction,
the DOM tree) Comment,
DocumentType

DocumentFragment Represents a "lightweight" Element,


Document object, which can ProcessingInstruction,
hold a portion of a document Comment, Text,
CDATASection,
EntityReference

DocumentType Provides an interface to the None


entities defined for the
document

ProcessingInstruction Represents a processing None


instruction

EntityReference Represents an entity reference Element,


ProcessingInstruction,
Comment, Text,
CDATASection,
EntityReference

Element Represents an element Element, Text,


Comment,
ProcessingInstruction,
CDATASection,
EntityReference

Attr Represents an attribute Text, EntityReference


Text Represents textual content in None
an element or attribute

CDATASection Represents a CDATA section in None


a document (text that will NOT
be parsed by a parser)

Comment Represents a comment None

Entity Represents an entity Element,


ProcessingInstruction,
Comment, Text,
CDATASection,
EntityReference

Notation Represents a notation declaredNone


in the DTD

Node Types - Return Values

The following table lists what the nodeName and the nodeValue properties will return for each
node type:

Node type nodeName returns nodeValue returns

Document #document null

DocumentFragment #document fragment null

DocumentType doctype name null

EntityReference entity reference name null

Element element name null

Attr attribute name attribute value

ProcessingInstruction target content of node

Comment #comment comment text


Text #text content of node

CDATASection #cdata-section content of node

Entity entity name null

Notation notation name null

NodeTypes - Named Constants

NodeType Named Constant

1 ELEMENT_NODE

2 ATTRIBUTE_NODE

3 TEXT_NODE

4 CDATA_SECTION_NODE

5 ENTITY_REFERENCE_NODE

6 ENTITY_NODE

7 PROCESSING_INSTRUCTION_NODE

8 COMMENT_NODE

9 DOCUMENT_NODE

10 DOCUMENT_TYPE_NODE

11 DOCUMENT_FRAGMENT_NODE

12 NOTATION_NODE

XML DOM - The Node Object

The Node object represents a node in the document tree.


The Node Object

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

The Node object represents a single node in the document tree.

A node can be an element node, an attribute node, a text node, or any other of the node types
explained in the "Node types" chapter.

Notice that while all objects inherits the Node properties / methods for dealing with parents and
children, not all objects can have parents or children. For example, Text nodes may not have
children, and adding children to such nodes results in a DOM error.

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

Node Object Properties


Property Description IE F O W3C

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


node

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


a node

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

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

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


a node

namespaceURI Returns the namespace URI of a No 1 9 Yes


node

nextSibling Returns the node immediately 5 1 9 Yes


following a node

nodeName Returns the name of a node, 5 1 9 Yes


depending on its type

nodeType Returns the type of a node 5 1 9 Yes

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


depending on its type

ownerDocument Returns the root element (document 5 1 9 Yes


object) for a node

parentNode Returns the parent node of a node 5 1 9 Yes

prefix Sets or returns the namespace No 1 9 Yes


prefix of a node

previousSibling Returns the node immediately before 5 1 9 Yes


a node

textContent Sets or returns the textual content No 1 No Yes


of a node and its descendants

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


descendants. IE-only property

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


descendants. IE-only property

Node Object Methods


Method Description IE F O W3C

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


end of the list of children of a
node

cloneNode() Clones a node 5 1 9 Yes

compareDocumentPosition() Compares the document No 1 No Yes


position of two nodes

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


implements the specialized
APIs of the specified feature
and version

getUserData(key) Returns the object associated No Yes


to a key on a this node. The
object must first have been
set to this node by calling
setUserData with the same
key

hasAttributes() Returns true if a node has any No 1 9 Yes


attributes, otherwise it returns
false

hasChildNodes() Returns true if a node has any 5 1 9 Yes


child nodes, otherwise it
returns false

insertBefore() Inserts a new child node 5 1 9 Yes


before an existing child node

isDefaultNamespace(URI) Returns whether the specified No Yes


namespaceURI is the default

isEqualNode() Checks if two nodes are equal No No No Yes

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


same node

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


feature is supported on a node

lookupNamespaceURI() Returns the namespace URI No 1 No Yes


matching a specified prefix

lookupPrefix() Returns the prefix matching a No 1 No Yes


specified namespace URI

normalize() Puts all text nodes underneath 5 1 9 Yes


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
removeChild() Removes a child node 5 1 9 Yes

replaceChild() Replaces a child node 5 1 9 Yes

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


on a node

XML DOM - The NodeList Object

The NodeList object represents an ordered list of nodes.

The NodeList object

The nodes in the NodeList can be accessed through their index number (starting from 0).

The NodeList keeps itself up-to-date. If an element is deleted or added, in the node list or the
XML document, the list is automatically updated.

Note: In a node list, the nodes are returned in the order in which they are specified in the XML.

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

NodeList Object Properties


Property Description IE F O W3C

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

NodeList Object Methods


Method Description IE F O W3C

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


node list
XML DOM - The NamedNodeMap Object

The NamedNodeMap object represents an unordered list of nodes.

The NamedNodeMap object

The nodes in the NamedNodeMap can be accessed through their name.

The NamedNodeMap keeps itself up-to-date. If an element is deleted or added, in the node list or
the XML document, the list is automatically updated.

Note: In a named node map, the nodes are not returned in any particular order.

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

NamedNodeMap Object Properties


Property Description IE F O W3C

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

NamedNodeMap Object Methods


Method Description IE F O W3C

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

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


and namespace)

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


index

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


name)

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


and namespace)

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


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

XML DOM - The Document Object

The Document object represents the entire XML document.

The Document object

The Document object is the root of a document tree, and gives us the primary access to the
document's data.

Since element nodes, text nodes, comments, processing instructions, etc. cannot exist outside the
document, the Document object also contains methods to create these objects. The Node objects
have a ownerDocument property which associates them with the Document where they were
created.

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

Document Object Properties


Property Description IE F O W3C

async Specifies whether downloading of an 5 1.59 No


XML file should be handled
asynchronously or not

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


the document

doctype Returns the Document Type 6 1 9 Yes


Declaration associated with the
document

documentElement Returns the root node of the 5 1 9 Yes


document

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


document

domConfig Returns the configuration used when No Yes


normalizeDocument() is invoked

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


document

implementation Returns the DOMImplementation No 1 9 Yes


object that handles this document

inputEncoding Returns the encoding used for the No 1 No Yes


document (when parsing)

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


document

nodeName Returns the name of a node 5 1 9 Yes


(depending on its type)

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

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


(depending on its type)

strictErrorChecking Sets or returns whether error- No 1 No Yes


checking is enforced or not

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


descendants. IE-only property

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


descendants. IE-only property

xmlEncoding Returns the XML encoding of the No 1 No Yes


document

xmlStandalone Sets or returns whether the No 1 No Yes


document is standalone

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


the document
Document Object Methods
Method Description IE FO W3C

adoptNode(sourcenode) Adopts a node from NoYes


another document to
this document, and
returns the adopted
node

createAttribute(name) Creates an attribute 6 1 9 Yes


node with the specified
name, and returns the
new Attr object

createAttributeNS(uri,name) Creates an attribute 9 Yes


node with the specified
name and namespace,
and returns the new
Attr object

createCDATASection() Creates a CDATA 5 1 9 Yes


section node

createComment() Creates a comment 6 1 9 Yes


node

createDocumentFragment() Creates an empty 5 1 9 Yes


DocumentFragment
object, and returns it

createElement() Creates an element 5 1 9 Yes


node

createElementNS() Creates an element No1 9 Yes


node with a specified
namespace

createEntityReference(name) Creates an 5 NoYes


EntityReference object,
and returns it

createProcessingInstruction(target,data) Creates a 5 9 Yes


ProcessingInstruction
object, and returns it

createTextNode() Creates a text node 5 1 9 Yes

getElementById(id) Returns the element 5 1 9 Yes


that has an ID attribute
with the given value. If
no such element exists,
it returns null

getElementsByTagName() Returns a NodeList of 5 1 9 Yes


all elements with a
specified name

getElementsByTagNameNS() Returns a NodeList of No1 9 Yes


all elements with a
specified name and
namespace

importNode(nodetoimport,deep) Imports a node from 9 Yes


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

normalizeDocument() NoYes

renameNode() Renames an element or NoYes


attribute node
XML DOM - The DocumentImplementation Object

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

The DocumentImplementation object

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

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

DocumentImplementation Object Methods


Method Description IE F O W3C

createDocument(nsURI, name, Creates a new DOM Document Yes


doctype) object of the specified doctype

createDocumentType(name, Creates an empty Yes


pubId, systemId) DocumentType node

getFeature(feature, version) Returns an object which Yes


implements the APIs of the
specified feature and version,
if the is any

hasFeature(feature, version) Checks whether the DOM Yes


implementation implements a
specific feature and version

XML DOM - The DocumentType Object

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

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

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

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

DocumentType Object Properties


Property Description IE F O W3C

entities Returns a NamedNodeMap 6 No 9 Yes


containing the entities declared in
the DTD

internalSubset Returns the internal DTD as a string No No No Yes

name Returns the name of the DTD 6 1 9 Yes

notations Returns a NamedNodeMap 6 No 9 Yes


containing the notations declared in
the DTD

systemId Returns the system identifier of the No 1 9 Yes


external DTD

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 IE F O W3C

data Sets or returns the content of this No Yes


processing instruction

target Returns the target of this processing No Yes


instruction

XML DOM - The Element Object

The Element object represents an element in an XML document.

The Element object

The Element object represents an element in an XML document. Elements may contain
attributes, other elements, or text. If an element contains text, the text is represented in a text-
node.

IMPORTANT! Text is always stored in text nodes. A common error in DOM processing is to
navigate to an element node and expect it to contain the text. However, even the simplest element
node has a text node under it. For example, in <year>2005</year>, there is an element node
(year), and a text node under it, which contains the text (2005).

Because the Element object is also a Node, it inherits the Node object's properties and methods.

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

Element Object Properties


Property Description IE F O W3C

attributes Returns a NamedNodeMap of attributes 5 1 9 Yes


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

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


element

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

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

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


element

namespaceURI Returns the namespace URI of the No 1 9 Yes


element

nextSibling Returns the node immediately following 5 1 9 Yes


the element

nodeName Returns the name of the node, depending 5 1 9 Yes


on its type

nodeType Returns the type of the node 5 1 9 Yes

ownerDocument Returns the root element (document 5 1 9 Yes


object) for an element

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

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


the element

previousSibling Returns the node immediately before the 5 1 9 Yes


element

schemaTypeInfo Returns the type information associated No Yes


with the element

tagName Returns the name of the element 5 1 9 Yes

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


element and its descendants

text Returns the text of the node and its 5 No No No


descendants. IE-only property

xml Returns the XML of the node and its 5 No No No


descendants. IE-only property

Element Object Methods


Method Description IE F O W3C

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


end of the list of children of
the node

cloneNode() Clones a node 5 1 9 Yes

compareDocumentPosition() Compares the document No 1 No Yes


position of two nodes

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


attribute

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


attribute (with a namespace)

getAttributeNode() Returns an attribute node as 5 1 9 Yes


an Attribute object

getAttributeNodeNS() Returns an attribute node No 9 Yes


(with a namespace) as an
Attribute object

getElementsByTagName() Returns a NodeList of 5 1 9 Yes


matching element nodes, and
their children

getElementsByTagNameNS() Returns a NodeList of No 1 9 Yes


matching element nodes (with
a namespace), and their
children

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


implements the specialized
APIs of the specified feature
and version

getUserData(key) Returns the object associated No Yes


to a key on a this node. The
object must first have been
set to this node by calling
setUserData with the same
key

hasAttribute() Returns whether an element 5 1 9 Yes


has any attributes matching a
specified name

hasAttributeNS() Returns whether an element No 1 9 Yes


has any attributes matching a
specified name and
namespace

hasAttributes() Returns whether the element 5 1 9 Yes


has any attributes

hasChildNodes() Returns whether the element 5 1 9 Yes


has any child nodes

insertBefore() Inserts a new child node 5 1 9 Yes


before an existing child node

isDefaultNamespace(URI) Returns whether the specified No Yes


namespaceURI is the default

isEqualNode() Checks if two nodes are equal No No No Yes

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


same node

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


feature is supported on the
element

lookupNamespaceURI() Returns the namespace URI No 1 No Yes


matching a specified prefix

lookupPrefix() Returns the prefix matching a No 1 No Yes


specified namespace URI

normalize() Puts all text nodes underneath 5 1 9 Yes


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

removeAttribute() Removes a specified attribute 5 1 9 Yes

removeAttributeNS() Removes a specified attribute No 1 9 Yes


(with a namespace)

removeAttributeNode() Removes a specified attribute 5 1 9 Yes


node

removeChild() Removes a child node 5 1 9 Yes

replaceChild() Replaces a child node 5 1 9 Yes

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


on the element

setAttribute() Adds a new attribute 5 1 9 Yes

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


namespace)

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

setAttributeNodeNS(attrnode) Adds a new attribute node 9 Yes


(with a namespace)

setIdAttribute(name,isId) If the isId property of the No Yes


Attribute object is true, this
method declares the specified
attribute to be a user-
determined ID attribute

setIdAttributeNS(uri,name,isId) If the isId property of the No Yes


Attribute object is true, this
method declares the specified
attribute (with a namespace)
to be a user-determined ID
attribute

setIdAttributeNode(idAttr,isId) If the isId property of the No Yes


Attribute object is true, this
method declares the specified
attribute to be a user-
determined ID attribute

XML DOM - The Attr Object

The Attr object represents an attribute of an Element object.

The Attr object

The Attr object represents an attribute of an Element object. The allowable values for attributes
are usually defined in a DTD.

Because the Attr object is also a Node, it inherits the Node object's properties and methods.
However, an attribute does not have a parent node and is not considered to be a child node of an
element, and will return null for many of the Node properties.

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

Attr Object Properties


Property Description IE F O W3C

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


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

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


the attribute

name Returns the name of the attribute 5 1 9 Yes

namespaceURI Returns the namespace URI of the No 1 9 Yes


attribute

nodeName Returns the name of the node, 5 1 9 Yes


depending on its type

nodeType Returns the type of the node 5 1 9 Yes

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


node, depending on its type

ownerDocument Returns the root element (document 5 1 9 Yes


object) for an attribute

ownerElement Returns the element node the No 1 9 Yes


attribute is attached to

prefix Sets or returns the namespace No 1 9 Yes


prefix of the attribute

schemaTypeInfo Returns the type information No No No Yes


associated with this attribute

specified Returns true if the attribute value is 5 1 9 Yes


set in the document, and false if it's
a default value in a DTD/Schema.

textContent Sets or returns the textual content No 1 9 Yes


of an attribute

text Returns the text of the attribute. IE- 5 No No No


only property

value Sets or returns the value of the 5 1 9 Yes


attribute

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


only property

XML DOM - The Text Object

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

The Text object

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

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

Text Object Properties


Property Description IE F O W3C

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


element or attribute

isElementContentWhitespace Returns true if the text node No No No Yes


contains content whitespace,
otherwise it returns false

length Returns the length of the text of 6 1 9 Yes


the element or attribute

wholeText Returns all text of text nodes No No No Yes


adjacent to this node,
concatenated in document order

Text Object Methods


Method Description IE F O W3C

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


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

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

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

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


and all adjacent text nodes with
the specified text

splitText() Splits this node into two nodes 6 1 9 Yes


at the specified offset, and
returns the new node that
contains the text after the offset

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

XML DOM - The CDATASection Object

The CDATASection object represents a CDATA section in a document.

Examples

The examples below use the XML file books.xml.


An external JavaScript is used to load the XML file.

createCDATASection() - Create a CDATA section node

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


Property Description IE F O W3C

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

length Returns the length of the CDATA section 6 1 No Yes

CDATASection Object Methods


Method Description IE F O W3C

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

deleteData() Deletes data from the 6 1 No Yes


node

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

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

splitText() Splits the CDATA node into 6 1 No


two nodes

substringData() Extracts data from the 6 1 No Yes


node

XML DOM - The Comment Object

The Comment object represents the content of comment nodes in a document.

Examples

The examples below use the XML file books.xml.


An external JavaScript is used to load the XML file.

createComment() - Create a comment node


The Comment object

The Comment object represents the content of comment nodes in a document.

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

Comment Object Properties


Property Description IE F O W3C

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

length Returns the length of the text of this node 6 1 9 Yes

Comment Object Methods


Method Description IE F O W3C

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

deleteData() Deletes data from the 6 1 9 Yes


node

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

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

substringData() Extracts data from the 6 1 9 Yes


node

The XMLHttpRequest Object

Examples

Load a textfile into a div element with XML HTTP

Make a HEAD request with XML HTTP

Make a specified HEAD request with XML HTTP

List data from an XML file with XML HTTP


The XMLHttpRequest Object Reference

Methods
Method Description

abort() Cancels the current request

getAllResponseHeaders() Returns the complete set of


http headers as a string

getResponseHeader("headername") Returns the value of the


specified http header

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


other optional attributes of a
request

The method parameter can have a


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

The URL parameter may be either a


relative or complete URL.

The async parameter specifies whether


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

setRequestHeader("label","value") Adds a label/value pair to the


http header to be sent

Properties
Property Description

onreadystatechange An event handler for an event that fires at every state


change

readyState Returns the state of the object:

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

responseXML Returns the response as XML. This property returns


an XML document object, which can be examined and
parsed using W3C DOM node tree methods and
properties

status Returns the status as a number (e.g. 404 for "Not


Found" or 200 for "OK")

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


"OK")

XML DOM Parse Error Object

Microsoft's parseError object can be used to retrieve error information from the Microsoft XML
parser.

To see how Firefox handles parser errors, check out the next page of this tutorial.

The parseError Object

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

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:

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

Try it yourself

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)

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

Try it yourself or just look at the XML file

The parseError Object's Properties

Property Description

errorCode Returns a long integer error code

reason Returns a string containing the reason for the error

Returns a long integer representing the line number for


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

srcText Returns a string containing the line that caused the error

url Returns the URL pointing the loaded document

filepos Returns a long integer file position of the error

XML DOM Parser Errors

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

Parser Error in Firefox

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

Unlike Internet Explorer, if Firefox encounters an error, it loads an XML document containing
the error description.

The root node name of the XML error document is "parsererror". This is used to check if there is
an error.

XML Error

In the following code we let the parser load an XML document that is not well-formed.

(You can read more about well-formed and valid XML in our XML tutorial)

xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.async=false;
xmlDoc.load("note_error.xml");

if (xmlDoc.documentElement.nodeName=="parsererror")
{
errStr=xmlDoc.documentElement.childNodes[0].nodeValue;
errStr=errStr.replace(/</g, "&lt;");
document.write(errStr);
}
else
{
document.write("XML is valid");
}

Example explained:

1. Load the xml file


2. Check if the nodeName of the root node is "parsererror"
3. Load the error string into a variable "errStr"
4. Replace "<" characters with "&lt;" before the error string can be
written as HTML

Try it yourself or just look at the XML file

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:

function loadXMLDocErr(dname)
{
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(dname);

if (xmlDoc.parseError.errorCode != 0)
{
alert("Error in line " + xmlDoc.parseError.line +
" position " + xmlDoc.parseError.linePos +
"\nError Code: " + xmlDoc.parseError.errorCode +
"\nError Reason: " + xmlDoc.parseError.reason +
"Error Line: " + xmlDoc.parseError.srcText);
return(null);
}
}
catch(e)
{
try //Firefox
{
xmlDoc=document.implementation.createDocument("","",null);
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"
4. If the errorCode property of the parseError object is different from "0",
alert the error and exit the function
5. 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
5. If not, return the XML document
You Have Learned XML DOM, Now What?

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.

Our XML DOM examples also represent a summary of this XML DOM tutorial.

What to Study Next?

Our recommendation is to learn about XSLT.

If you want to learn more about validating XML, we recommend DTD and XML Schema.

Below is a short description of each subject.

XSLT (XML Stylesheet Language Transformations)


XSLT is the style sheet language for XML files.

With XSLT you can transform XML documents into other formats, like XHTML.

If you want to learn more about XSLT, please visit our XSLT tutorial.

XML DTD (Document Type Definition)

The purpose of a DTD is to define what elements, attributes and entities is legal in an XML
document.

With DTD, each of your XML files can carry a description of its own format with it.

DTD can be used to verify that the data you receive, and your own data, is valid.

If you want to learn more about DTD, please visit our DTD tutorial

XML DOM Examples

XML DOM Parsing

The examples below use the XML file books.xml.

Load and parse an XML file


Load and parse an XML string

Examples explained

XML DOM Properties and Methods

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 - External parsing script


Load and parse an XML string - External parsing script

Examples explained
XML DOM Accessing Nodes

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


Loop through nodes using the length property
See the node type of an element
Loop through element nodes
Loop through element nodes using node relationships

Examples explained

XML DOM Node Information

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


Get the text from a text node
Change the text in a text node
Get the node name and type of an element node

Examples explained

XML DOM Node List and Attribute List

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


Loop through nodes using the length property
Get the attribute of an element

Examples explained

XML DOM Traversing Node Tree

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


Examples explained

XML DOM Browser Differences

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 - Different results in IE and other browsers
Ignore empty text between nodes

Examples explained

XML DOM Navigating Nodes

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


Get the first child element of a node
Get the last child element of a node
Get the next sibling element of a node
Get the previous sibling element of a node

Examples explained

XML DOM Get Node Values

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 text value


Get an attribute's text value

Examples explained

XML DOM Change Node Values

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.
Change an elements text node
Change an attributes value using setAttribute
Change an attributes value using nodeValue

Examples explained

XML DOM Remove Nodes

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Remove an element node


Remove the current element node
Remove a text node
Clear the text of a text node
Remove an attribute by name
Remove attributes by object

Examples explained

XML DOM Replace Nodes

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Replace an element node


Replace data in a text node

Examples explained

XML DOM Create Nodes

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Create an element node


Create an attribute node using createAttribute
Create an attribute node using setAttribute
Create a text node
Create a CDATA section node
Create a comment node

Examples explained
XML DOM Add Nodes

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Add a node after the last child node


Add a node before a specified child node
Add a new attribute
Add data to a text node

Examples explained

XML DOM Clone Nodes

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

Copy a node and append it to an existing node

Examples explained

XML DOM Clone Nodes

The examples below use the XML file books.xml.


A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.

XML HTTP communication with a server while typing input


Load a textfile into a div element with XML HTTP
Make a HEAD request with XML HTTP
Make a specified HEAD request with XML HTTP
List data from an XML file with XML HTTP

Das könnte Ihnen auch gefallen