From http://www.w3schools.com (Copyright Refsnes Data)

XML DOM Load Function

prev next

The code for loading XML documents can be stored in a function.

The function described below, is used in all examples in this tutorial.


An XML Load Function - loadXMLDoc()

The XML DOM contains methods (functions) to traverse XML trees, access, insert, and delete nodes.

However, before an XML document can be accessed and manipulated, it must be loaded into an XML DOM object.

The previous chapter demonstrated how to load XML documents. To make it simpler to maintain this code, it should be written as a function:

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 function above can be stored in the <head> section of an HTML page, and called from a script in the page.

Try it yourself


An External Load Function

To make the function above even easier to maintain, and to make sure the same code is used in all pages, it can be stored in an external file.

We have called the file "loadxmldoc.js"

The file can be loaded in the <head> section of an HTML page, and loadXMLDoc() can be called from a script in the page:

<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

lamp The function described above, is used in all examples in this tutorial


An XML Load Function - loadXMLString()

A similar function can be used to load an XML string (instead an XML file):

function loadXMLString(txt) 
{
try //Internet Explorer
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
  xmlDoc.loadXML(txt);
  return(xmlDoc); 
  }
catch(e)
  {
  try //Firefox, Mozilla, Opera, etc.
    {
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(txt,"text/xml");
    return(xmlDoc);
    }
  catch(e) {alert(e.message)}
  }
return(null);
}

To make the function above easier to maintain, and to make sure the same code is used in all pages, it can be stored in an external file.

We have stored in in a file called "loadxmlstring.js".

Try it yourself


prev next

From http://www.w3schools.com (Copyright Refsnes Data)