XML DOM Load Functions

You can store the code for loading XML documents in a separate function.

Loading Function

The XML DOM contains methods (functions) for traversing the XML tree and accessing, inserting, and deleting nodes.

Before accessing and processing the XML document, it must be loaded into the XML DOM object.

The previous section demonstrated how to load an XML document. To avoid rewriting code repeatedly due to loading the document, you can store the code in a separate JavaScript file:

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 above function is stored in a file named "loadxmldoc.js".

The following example has a link to "loadxmldoc.js" in its <head> section and uses the loadXMLDoc() function to load the XML document ("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 is loaded, ready for use");
</script>
</body>
</html>

Try It Yourself (TIY)