Using Java Script to Display XML Data
By Stephen Bucaro
When you load an XML document into Internet Explorer, it uses the XML Document Object
Model (DOM) to store the document's data in a hierarchical structure that mirrors the
structure of the XML document. The (DOM) consists of programming objects that represent
the elements of an XML document. You can use Java Script to access the properties and
methods of the objects to display the XML document's data as an html page.
In this article, you'll learn how to link an XML document to an html page and how to
access the the XML document's elements using Java Script. Then You'll create a script
that you can use to traverse any XML document to display information about its elements.
Lastly, you'll create a script that you can use to check any XML document for errors.
For our first example, open a new text file using Windows Notepad or your favorite ASCII
text editor and enter or paste in the following code:
<?xml version="1.0"?>
<book>
<title>XML in a Nutshell</title>
<publisher>O'Reilly</publisher>
<author>Scott Means</author>
<isbn>0596007647</isbn>
<pubdate>2004</pubdate>
<price>26.37</price>
</book>
Save the file with the name "books.xml". This creates a simple XML document containing one
element, the root element named <book>.
Open another new text file and enter or paste in the following code:
<html>
<head>
</head>
<body onload="showBook()">
<xml id="book" src="Book.xml"></xml>
</body>
</html>
Save the file with the name "example1.htm". This creates a simple webpage containing an
html tag named <xml>. This html element links the XML document to the webpage.
If you needed
to access more than one XML document from a webpage, you could insert a link to each XML document.
Next, skip a line below the html element named xml, and enter or paste in the following code:
Title: <span id="title"></span><br />
Publisher: <span id="publisher"></span><br />
Author: <span id="author"></span><br />
ISBN: <span id="isbn"></span><br />
Pub Date: <span id="pubdate"></span><br />
Price: <span id="price"></span>
This creates a group of html <span> elements. We'll use Java Script to access these
spans by id to display the XML document's data on the webpage.
|