Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

XML DOM load function


May 27, 2021 XML DOM


Table of contents


XML DOM load function

The code for loading XML is available in XML, so how do you manage it? Let's take a look at this section!

The code in the load XML documentation can be stored in a function.


LoadXMLDoc() function

To make the code on the previous page easy to maintain (check the old browser), 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 section of the HTML page and called from the script on the page.

XML DOM load function The functions described above are used for all XML document instances in this tutorial!


External JavaScript for loadXMLDoc().

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

The file name is "loadxmldoc .js" and the head section in the HTML page is loaded. The script on the page then calls the loadXMLDoc() function.

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

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

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

code goes here.....

</script>

</body>
</html>

Try it out . . .

How to get data from an XML file is explained in the next chapter.


LoadXMLString() function

To make the code on the previous page easy to maintain (check the old browser), 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 section of the HTML page and called from the script on the page.

XML DOM load function The functions described above are used for all XML string instances in this tutorial!


LoadXMLString() external JavaScript

We've stored the loadXMLString() function in a file called "loadxmlstring.js" file.

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