Rishi Jogle
Rishi Jogle

Reputation: 287

How to Write into XML using AJAX / Javascript

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

Upvotes: 0

Views: 3218

Answers (1)

Andris
Andris

Reputation: 27885

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.

Upvotes: 1

Related Questions