Convert string to xml and xml to string using javascript

06 Sep 2022
Intermediate
17K 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> 

Learn to Crack Your Technical Interview

Accept cookies & close this