Convert XML Document to String in JavaScript  


Often we want to convert the XMLObject generated by JavaScript in memory to String, this is essential as a developer we would like to test whether the generated XML is as per the required XML Structure This article contains javascript code snippet that will allow you to convert XML Object to String.

If you have still not learn on XML in Javascript you can check out this pages

NOTE:
Syntax for XML Document Conversion is different for Internet Explorer and Firefox Browsers


 


Microsoft Internet Explorer

   <script type="text/javascript">
	function load_xml_content_string(xmlData) {
		if (window.ActiveXObject) {
			//for IE
			xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async="false";
			xmlDoc.loadXML(xmlData);
			return xmlDoc;
		} else if (document.implementation && document.implementation.createDocument) {
			//for Mozila
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(xmlData,"text/xml");
			return xmlDoc;
		}
	}
	var xmlObject = load_xml_content_string("<employee><age>12</age></employee>");
 
	var xmlString = xmlObject.xml;
	alert(string);
   </script>


 


Firefox

   <script type="text/javascript">
	function load_xml_content_string(xmlData) {
		if (window.ActiveXObject) {
			//for IE
			xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async="false";
			xmlDoc.loadXML(xmlData);
			return xmlDoc;
		} else if (document.implementation && document.implementation.createDocument) {
			//for Mozila
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(xmlData,"text/xml");
			return xmlDoc;
		}
	}
	var xmlObject = load_xml_content_string("<employee><age>12</age></employee>");
 
	var xmlString = (new XMLSerializer()).serializeToString(xmlObject);
	alert(xmlString);
   </script>





Related Articles:

Categories: Javascript Tags: ,
  1. March 2nd, 2009 at 20:44 | #1

    great help, great info, saved me so much..
    thanks

  2. December 25th, 2009 at 21:33 | #2

    How to parse XML to text content in ASP ??

  3. December 25th, 2009 at 21:34 | #3

    Are you have javascript class to overide XML method for IE & FF ?

  4. December 29th, 2009 at 03:50 | #4

    Here is a small library which allows JavaScript Xml Document and JavaScript Xpath manipulation. It might be useful: JavaScript Xml and XPath

  5. Dee
    December 28th, 2010 at 14:21 | #5

    this only works if you hard code the xml into the script.
    does not work with variable passing in value.

  6. Paul
    May 24th, 2012 at 06:41 | #6

    var xmlString = (new XMLSerializer()).serializeToString(xml);

  7. mitya
    December 11th, 2012 at 08:38 | #7

    thanks, it really help me

  1. March 29th, 2010 at 20:26 | #1

 

Page optimized by WP Minify WordPress Plugin