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:

About Hitesh Agrawal

Wait... checking
Tagged , . Bookmark the permalink.

8 Responses to Convert XML Document to String in JavaScript

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

  2. boing says:

    How to parse XML to text content in ASP ??

  3. boing says:

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

  4. Mike says:

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

  5. Pingback: xml parser library

  6. Dee says:

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

  7. Paul says:

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

  8. mitya says:

    thanks, it really help me

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>