Easy Tutorial
❮ Dom Errors Dom Met Element Removeattribute ❯

XML DOM Load Function


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


loadXMLDoc() Function

To make the code from the previous page easier to maintain (check for old browsers), it should be written as a function:

loadxmldoc.js File Code:

function loadXMLDoc(dname)
{
    if (window.XMLHttpRequest)
    {
        xhttp=new XMLHttpRequest();
    }
    else
    {
        xhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET",dname,false);
    xhttp.send();
    return xhttp.responseXML;
}

The function above can be stored in the <head> section of an HTML page and called from scripts within the page.

The function described above is used for all XML document examples in this tutorial!


External JavaScript for loadXMLDoc()

To make the above code easier to maintain and ensure the same code is used across all pages, we store the function in an external file.

The file is named "loadxmldoc.js" and is loaded in the <head> section of the HTML page. Then, the loadXMLDoc() function is called from scripts within the page.

The following example uses the loadXMLDoc() function to load books.xml:

Example

<html>
<head>
<script src="loadxmldoc.js"></script>
</head>
<body>

<script>
xmlDoc=loadXMLDoc("books.xml");

code goes here.....

</script>

</body>
</html>

How to retrieve data from an XML file will be explained in the next chapter.


loadXMLString() Function

To make the code from the previous page easier to maintain (check for old browsers), it should be written as a function:

loadxmlstring.js File Code:

function loadXMLString(txt) 
{
    if (window.DOMParser)
    {
        parser=new DOMParser();
        xmlDoc=parser.parseFromString(txt,"text/xml");
    }
    else 
    {
        // Internet Explorer
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async=false;
        xmlDoc.loadXML(txt); 
    }
    return xmlDoc;
}

The function above can be stored in the <head> section of an HTML page and called from scripts within the page.

The function described above is used for all XML string examples in this tutorial!


External JavaScript for loadXMLString()

We have stored the loadXMLString() function in a file named "loadxmlstring.js".

Example

<html>
<head>
<script src="loadxmlstring.js"></script>
</head>
<body>
<script>
text="<bookstore>"
text=text+"<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
text=text+"</bookstore>";

xmlDoc=loadXMLString(text);

code goes here.....
</script>
</body>
</html>
❮ Dom Errors Dom Met Element Removeattribute ❯