XML Parser In JavaScript

Introduction

All 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 has properties and methods used to manipulate the XML.

Parsing a String to XML  

var text = "<author>" +  
         "<FirstName>Bob</FirstName>" +  
         "<LastName>Ross</LastName>" +  
         "</author>";  
  
     var parser = new DOMParser();  
     var xmlDoc = parser.parseFromString(text, "text/xml");  
 console.log(xmlDoc); 

From the above code, you can observe that the DomParser() object is created to convert the string into XML using the -method parseFromString.

 

The above image shows the XML, which is converted from the string.

var text = "<author>" +  
           "<FirstName>Bob</FirstName>" +  
           "<LastName>Ross</LastName>" +  
           "</author>";  
  
       var parser = new DOMParser();  
       var xmlDoc = parser.parseFromString(text, "text/xml");  
   console.log(xmlDoc);  
   console.log(xmlDoc.all)    
   var text = "<author>" +  
           "<FirstName>Bob</FirstName>" +  
           "<LastName>Ross</LastName>" +  
           "</author>";  

All the properties are used to get a list of nodes in XML.

var text = "<author>" +  
            "<FirstName>Bob</FirstName>" +  
            "<LastName>Ross</LastName>" +  
            "</author>";  
  
        var parser = new DOMParser();  
        var xmlDoc = parser.parseFromString(text, "text/xml");  
    console.log(xmlDoc);  
    console.log(xmlDoc.all)  
    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

<script>  
   
        var text = "<author>" +  
            "<FirstName>Bob</FirstName>" +  
            "<LastName>Ross</LastName>" +  
            "</author>";  
  
        var parser = new DOMParser();  
        var xmlDoc = parser.parseFromString(text, "text/xml"); //string to XML  
    console.log(xmlDoc);  
    console.log(xmlDoc.all)  
    console.log(xmlDoc.getElementsByTagName("FirstName")[0].textContent);  
  
    var xmlString = (new XMLSerializer()).serializeToString(xmlDoc); // XML to String   
    console.log(xmlString);  
  
   </script>  

XMLSerialzer() object is used to parse the XML to string using the serializeToString method.

Conclusion

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