Coding, HTML/XHTML/HTML5

DOM, XML and an XML Parser

DOM represents a document as a tree of nodes including elements, text data, comments, CDATA sections and so on. The elements in this tree can be HTML elements or XML elements like <employee> or <student>. So these elements could also be accessed and looked at or parsed.

Loading an XML document:

To load the document we create an instantiation of Microsoft’s XML parser using the ActiveXObject. Once the object is created, then the appropriate XML document is loaded into the memory. The following code snippet explains this:

var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
xmldoc.async = false;
xmldoc.load("staff.xml");

In case of Mozilla browsers the instantiation code will be:

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

Once the xml document is loaded into the memory, DOM is used to manipulate it.
For example, we have a xml file staff.xml, which looks like:

<?xml version = "1.0" encoding="ISO-8859-1"?>
<directory>
<employee>
 <name>James Fernandex</name>
 <title> Controller of Examination</title>
 <phone>033-33434459</phone>
 <email>jfernandez@democomp.com</email>
</employee>
</directory>
</xml>

We can access the root element of the document i.e. <directory> using the following code:
var rootelement = xmldoc.documentElement;

The following code explains this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<tittle> XML Parser Demo</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
</head>
<body>
<script type="text/jscript">
<!--
var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
xmldoc.async = false;
xmldoc.load("staff.xml");
var rootelement = xmldoc.documentElement;
//-->
</script>
<form action="#" method="get">
<input type = "button" value="Node Name" onclick="alert(rootelement.nodeName);"/>
</form>
</body>
</html>