Javascript - Javascript string to XML object:

Turns a string into an xml object:

<script type="text/javascript">
	//sample  xml:
 
	var text="<note>";
	text=text+"<content>whatever</content>";
	text=text+"</note>";
 
	//function : 
            function StringtoXML(text){
                if (window.ActiveXObject){
                  var doc=new ActiveXObject('Microsoft.XMLDOM');
                  doc.async='false';
                  doc.loadXML(text);
                } else {
                  var parser=new DOMParser();
                  var doc=parser.parseFromString(text,'text/xml');
                }
                return doc;
            }
 
	//example of application:
	var doc = StringtoXML(text);
</script>
Reply:
 
 
 
 
thank you!!!
Thank to help me :)
Thanks for this - just what I needed!
This object helps me to convert an xml object to string, and to convert string to xml, to parse it and save to db for example, it works on IE an firefox, safari, opera, etc.

var _xml = {
_str2xml : function(strXML){
if (window.ActiveXObject)
{
var doc=new ActiveXObject(\"Microsoft.XMLDOM\");
doc.async=\"false\";
doc.loadXML(strXML);
}
// code for Mozilla, Firefox, Opera, etc.
else
{
var parser=new DOMParser();
var doc=parser.parseFromString(strXML,\"text/xml\");
}// documentElement always represents the root node
return doc;
},
_xml2string : function(xmlDom){
var strs = null;
var doc = xmlDom.documentElement;
if(doc.xml == undefined){
strs = (new XMLSerializer()).serializeToString(xmlDom);
}else strs = doc.xml;
return strs;

}
}

var xmlDoc = _xml._str2xml(\"\");
alert(xmlDoc.childNodes.length);

alert(\"Xml string is:\" + _xml._xml2string(xmlDoc));
rendered @ Wed Mar 26 21:52:45 CET 2014