i am makin an editor for CMS . now i want to create an XML file and i wnt to write content into XML file
-
1You can't do that using only JavaScript. You have to pass the XML file e.g. as a string to e.g. a PHP script. //I assumed that you want to create a XML file on a server... Right?user882255– user8822552011-08-12 10:11:56 +00:00Commented Aug 12, 2011 at 10:11
-
No i am not using PHP . I am using only javascript and Ajax . so is it possible ?Rishi Jogle– Rishi Jogle2011-08-16 06:47:19 +00:00Commented Aug 16, 2011 at 6:47
1 Answer
JavaScript can handle XML very well, actually Ajax (XMLHttpRequest) was at first meant to deal with ajax only later plain text prevailed.
You can use the following functions to handle XML
Convert XML node to string
function XMLToStr(xmlNode){
try{ // Mozilla, Webkit, Opera
return new XMLSerializer().serializeToString(xmlNode);
}catch(E) {
try { // IE
return xmlNode.xml;
}catch(E2){}
}
}
Convert a String to XML object
function strToXML(xmlString){
var dom_parser = ("DOMParser" in window && (new DOMParser()).parseFromString) ||
(window.ActiveXObject && function(_xmlString) {
var xml_doc = new ActiveXObject('Microsoft.XMLDOM');
xml_doc.async = 'false';
xml_doc.loadXML(_xmlString);
return xml_doc;
});
if(!dom_parser){
return false;
}
return dom_parser.call("DOMParser" in window && (new DOMParser()) || window, xmlString, 'text/xml');
}
Usage:
Convert a string into XML node and fetch some values from it
var xml = strToXML('<root><name>abc</name></root>');
console.log(xml.firstChild.nodeName); // root
console.log(xml.firstChild.firstChild.firstChild.nodeValue); // abc
To load XML object from an Ajax call instead of plain text or JSON, use responseXML instead of responseText - the only caveat being that the XML needs to be correctly sent from the server, ie. the content-type needs to be correct and the XML must be valid.