Latest web development tutorials

XML DOM loading function

Loading XML document code may be stored in a function.


loadXMLDoc () function

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

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 above functions can be stored in the page's HTML <head> section, and calls from the pages of the script.

lampFunction described above, for this tutorial all XML document instance!


loadXMLDoc () external JavaScript

To make it easier to maintain the code above, to ensure that all use the same code in the page, in an external file we function storage.

File named "loadxmldoc.js", and in the head part of the HTML page is loaded. Then, in the page script calls loadXMLDoc () function.

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

Examples

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

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

code goes here.....

</script>

</body>
</html>

try it"

How to get the data from the XML file, we will explain in the next chapter.


loadXMLString () function

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

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 above functions can be stored in the page's HTML <head> section, and calls from the pages of the script.

lampFunction described above, for this tutorial all XML string instances!


loadXMLString () external JavaScript

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

Examples

<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>

try it"