JavaScript and XML

To demonstrate JavaScript, XML, and the DOM in action, let’s use Internet Explorer 5.5 or better to load an XML document containing our employee directory and see if we can manipulate it. First, to load in the document we create an instantiation of Microsoft’s XML parser using the JScript-specific ActiveXobject. Once the object is created, we load the appropriate XML document into memory. In this case, it is the pure XML file of employee records we saw earlier without style sheets or other references.
var xmldoc = new ActiveXObject("Microsoft.XMLDOM");

xmldoc.async = false;

xmldoc.load("staff2.xml");
Once loaded, we can then use the DOM to manipulate it. For example, we can access the root element of the document (<<directory>>) using
var rootElement = xmldoc.documentElement;
then we might alert out its nodeName property as shown in this example.
<<!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>>

<<title>>XML 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="show node"

 onclick="alert(rootElement.nodeName);" />>

<</form>>

<</body>>

<</html>>
 
 
 
 
 
 
function deleteLastElement()

{

  var rootElement = xmldoc.documentElement;

  if (rootElement.hasChildNodes())

     rootElement.removeChild(rootElement.lastChild);

}
 
 
 
Really the only difference here is the use of the xmldoc object we created to reference the XML document rather than just plain document, which would reference the HTML Document object. Otherwise, the manipulations are the same as with HTML.