XML Parser In JavaScript

From this blog, you will learn how to parse a string to XML and vice versa.

Introduction

 
All the modern browsers contain built-in XML parsers which are used to convert a string into an XML DOM object and vice versa. The XML DOM object contains properties and methods which are used to manipulate the XML.

Parsing a String to XML 
  1. var text = "<author>" +  
  2.          "<FirstName>Bob</FirstName>" +  
  3.          "<LastName>Ross</LastName>" +  
  4.          "</author>";  
  5.   
  6.      var parser = new DOMParser();  
  7.      var xmlDoc = parser.parseFromString(text, "text/xml");  
  8.  console.log(xmlDoc);  
From the above code, you can observe that the DomParser() object is created which is used to convert the string into XML using the -method parseFromString.
 
 
 
The above image shows the XML which is converted from string.
  1. var text = "<author>" +  
  2.            "<FirstName>Bob</FirstName>" +  
  3.            "<LastName>Ross</LastName>" +  
  4.            "</author>";  
  5.   
  6.        var parser = new DOMParser();  
  7.        var xmlDoc = parser.parseFromString(text, "text/xml");  
  8.    console.log(xmlDoc);  
  9.    console.log(xmlDoc.all)    
  10.    var text = "<author>" +  
  11.            "<FirstName>Bob</FirstName>" +  
  12.            "<LastName>Ross</LastName>" +  
  13.            "</author>";  
All the properties are used to get a list of nodes in XML.
  1. var text = "<author>" +  
  2.             "<FirstName>Bob</FirstName>" +  
  3.             "<LastName>Ross</LastName>" +  
  4.             "</author>";  
  5.   
  6.         var parser = new DOMParser();  
  7.         var xmlDoc = parser.parseFromString(text, "text/xml");  
  8.     console.log(xmlDoc);  
  9.     console.log(xmlDoc.all)  
  10.     console.log(xmlDoc.getElementsByTagName("FirstName")[0].textContent);  
The getElementsByTagName method is used to get the information about the node based on the Tag Name.
 
Parsing XML to String
  1. <script>  
  2.    
  3.         var text = "<author>" +  
  4.             "<FirstName>Bob</FirstName>" +  
  5.             "<LastName>Ross</LastName>" +  
  6.             "</author>";  
  7.   
  8.         var parser = new DOMParser();  
  9.         var xmlDoc = parser.parseFromString(text, "text/xml"); //string to XML  
  10.     console.log(xmlDoc);  
  11.     console.log(xmlDoc.all)  
  12.     console.log(xmlDoc.getElementsByTagName("FirstName")[0].textContent);  
  13.   
  14.     var xmlString = (new XMLSerializer()).serializeToString(xmlDoc); // XML to String   
  15.     console.log(xmlString);  
  16.   
  17.    </script>  
XMLSerialzer() object is used to parse the XML to string using serializeToString method.

Conclusion

 
We saw how to parse a string to XML and XML to string using the JavaScript. I hope you have enjoyed this blog. Your valuable feedback, questions, or comments about this article are always welcomed.