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
- JavaScript XML Parsing on Microsoft Internet Explorer
- JavaScript XML Parsing on Mozilla Firefox / Opera Browsers
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:
- Java Plugin detection using JavaScript
- Debugging JavaScript Code for Errors
- JSON in Javascript
- How to make sequential ajax call
- Global Objects in Javascript
- Showing Dynamic DIV above HTML SELECT Control
- Declaring Variables in Javascript
- Parsing XML Documents in JavaScript
- Dynamic Variables in Javascript
- What is JavaScript
great help, great info, saved me so much..
thanks
How to parse XML to text content in ASP ??
Are you have javascript class to overide XML method for IE & FF ?
Here is a small library which allows JavaScript Xml Document and JavaScript Xpath manipulation. It might be useful: JavaScript Xml and XPath
this only works if you hard code the xml into the script.
does not work with variable passing in value.
var xmlString = (new XMLSerializer()).serializeToString(xml);
thanks, it really help me