Wednesday, May 24, 2017

To read the XML using JavaScript (works in all browsers)

In this blog, I have explained the steps to read the XML using JavaScript. 

The below XML has Root "Tasks" and nodes "TaskName".

Input XML:
<?xml version="1.0" ?>
<Tasks>   
    <TaskName id="PromoteBestPractice">Promoted best practices</TaskName>
    <TaskName id="PromoteBeneEngage">Promoted beneficiary engagement and self-management</TaskName>
    <TaskName id="SustainPlan">Worked on a sustainability plan</TaskName>
</Tasks>


This JavaScript function accepts the xmlPath and xmlnodename as parameters. 

JavaScript:

function ChangeLabelTaskNameFrmXML(xmlPath,xmlnodename) {  
  
    var request = new XMLHttpRequest();
    request.open("GET", xmlPath, false);
    request.send();
    var xmldoc = request.responseXML; 
   //Extract the different values using a loop.     
    var xmlnode = xmldoc.getElementsByTagName(xmlnodename);

   // To read the xml nodes in XML file
    for (var i = 0; i < xmlnode.length; i++) {
        var lbltaskname = xmlnode[i].getAttribute('id');
        var newlbltaskname = xmlnode[i].textContent;
        alert ("Key:" + lbltaskname + "; Value: " + newlbltaskname );
   } 


Final Output will be displayed in message box with Key and Value as shown below.

Output:

Key: PromoteBestPractice; Value: Promoted best practices

No comments:

Post a Comment

Augmented Reality and Virtual Reality

Here is the quick overview of Augmented Reality and Virtual Reality, also have explained how it is being used today and how it can chan...