0

i am makin an editor for CMS . now i want to create an XML file and i wnt to write content into XML file

2
  • 1
    You 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? Commented Aug 12, 2011 at 10:11
  • No i am not using PHP . I am using only javascript and Ajax . so is it possible ? Commented Aug 16, 2011 at 6:47

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.