Thursday 28 December 2017

How to working with XML Parsers in XML

An XML parser reads and updates an XML document by loading the document into the computers memory and then manipulate it using the DOM node-tree structure. It tests an XML document to check whether or not the document is well formed against the given DTD.  Now here we create an XML file employees.xml which is parsed by an XML parser.
<?XML version="1.0" encoding="ISO-8859-1"?>
<Employee>
<First_name>Ambrish</First_name>
<Middle_name>kumar </Middle_name>
<Last_name>singh</Last_name>
<Age>25</Age>
<Employee>
Next we use the SAX parser to check whether the XML document is well-formed or not. The SAX parser is available in the form of three jar files.
Like :
saxons.jar
saxon-jdom.jar
saxon-xml-apis.jar

Now we need to set the path of preceding JAR file in the classpath variable of environment variable in your system to run the SAX parser.

Here we have to create an HTML file xmlparser.html which uses SAX libraries to parse the employees.xml. That shows the code of the xmlparser.html file.

/////xmlparser.html file /////
<!doctype html>
<head>
<SCRIPT type="text/javascript">
var xmlParseDoc;
function loadParseXML()
{
if(window.ActiveXObject){
xmlParseDoc=new ActiveXObject("Microsoft.XMLDOM";
xmlParseDoc.async=false;
xmlParseDoc.load("employees.xml") ;
getmessage() ;
}
else if (document.implementation & & document.implementation.createDocument){
xmlParseDoc=document.implementation.createDocument("","",null);
xmlParseDoc.load("employees.xml") ;
xmlparser of.onload=getmessage;
}else {
alert('The script is not Compatible with your browser ') ;
}
} function getmessage()
{
document. getElementById("FirstName").innerHTML=xmlParseDoc.getElementByTagName("FirstName")[0].childNodes[0].nodeValue;
document.getElementById("MiddleName").innerHTML=
xmlParseDoc.getElementByTagName("MiddleName") [0].childNode[0].nideValue;
document. getElementById("LastName"). innerHTML=
xmlParseDoc.getElementsByTagName("LastName")[0].childNodes[0].nodeValue;
document.getElementById("Age").innerHTML=
xmlParseDoc.getElementsByTagName("Age")[0].childNodes[0].nodeValue;
}
</SCRIPT>
</head>
<body onload="loadParseXML()" >
<h1>Employee Details </h1>
<p><b>FirstName:</b>
<span id="FirstName"></span><br>
<b>Middle Name :</b><span id="MiddleName"></span><br>
<b>last Name :</b><span id="LastName"></span><br>
<b>Age:</b><span id="Age"></span>
</p>
</body>
</html>

We have used JavaScript to create two methods, loadParseXML()  and getMessage().
The loadParseXML() Method create an ActiveXObject object, xmlParseDoc, to load the XML document, employees.xml. Then, it calls the getMessage() method to retrieve the data stored in the XML document and display it on the browser. 

No comments:

Post a Comment