XML DOM Tree Example

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

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

The DOM presents an XML document as a tree-structure.


Knowing the XML DOM is a must for anyone working with XML.
Start learning the XML DOM now!
XML DOM Tree Example



XML DOM Objects Reference
At W3Schools you will find a complete DOM reference, with all the objects and their properties and methods.
XML DOM Reference
XML DOM Examples
Learn by 50 examples! With our editor, you can edit the source, and click on a test button to view the result.
Try-It-Yourself!
XML Exam - Get Your Diploma!

W3Schools' Online Certification Program
The perfect solution for professionals who need to balance work,
family, and career building.
More than 3500 certificates already issued!
The HTML Certificate documents your knowledge of HTML, XHTML, and CSS.
The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.
The XML Certificate documents your knowledge of XML, XML DOM and XSLT.
The ASP Certificate documents your knowledge of ASP, SQL, and ADO.
The PHP Certificate documents your knowledge of PHP and SQL (MySQL).



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 Home page.

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.


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!

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



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

Parsing an XML String - A Cross browser Example
The following code loads and parses an XML string:
Example
<html>
<body>
<script type="text/javascript">
text="<bookstore>"
text=text+"<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
text=text+"</bookstore>";

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


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

You might also like