×

Convert string to xml and xml to string using javascript

Shailendra Chauhan  Print   1 min read  
13 Jun 2012
22 Aug 2020
Intermediate
79.1K Views

Sometimes we need to parse xml into string and string into xml. Different browsers parse xml to string and vice-versa in different ways. Here, I am sharing cross browser compatible methods to parse xml.

Parse XML to String

 

<script type="text/javascript" language="javascript">
function XMLToString(oXML)

{
 //code for IE
 if (window.ActiveXObject) {
 var oString = oXML.xml; return oString;
 } 
 // code for Chrome, Safari, Firefox, Opera, etc.
 else {
 return (new XMLSerializer()).serializeToString(oXML);
 }
 }

</script> 

Parse String to XML

 <script type="text/javascript" language="javascript">
function StringToXML(oString) {
 //code for IE
 if (window.ActiveXObject) { 
 var oXML = new ActiveXObject("Microsoft.XMLDOM"); oXML.loadXML(oString);
 return oXML;
 }
 // code for Chrome, Safari, Firefox, Opera, etc. 
 else {
 return (new DOMParser()).parseFromString(oString, "text/xml");
 }
}
</script> 
Share Article

Take our free skill tests to evaluate your skill!

In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.

Training Schedules
+91 9999123502
Accept cookies & close this