Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Thursday, June 16, 2011

XML to JSON and JSON to XML Conversion in Javascript

When we deal with today's highly ajax based web application developments, dealing with XMLs within your page might be a little bit tedious task. As all of us know, JavaScript doesn't have a proper way to deal with XMLs(although recent specs supports E4X, it hasn't implemented in all browsers). If we can convert the XML into a JSON format, then it will be a great relief for web developers.

Although there are many XML to JSON notations available, all of them tends to ignore xml namespaces, but Badgerfish. So, I thought of writing a JavaScript code which does the XML to JSON conversion and wise-versa. If you want to get the Javascript code for XML to JSON, then go though my blog post XML to BadgerFish Conversion in Javascript. In this post, I will give you the function which converts JSON back to it's original XML.

Using these xml2bf and bf2xml functions, you will get the most flexibility with XML in your web developments.
function bf2xml(json) {
    if (typeof json !== "object") return null;
    var cloneNS = function(ns) {
        var nns = {};
        for (var n in ns) {
            if (ns.hasOwnProperty(n)) {
                nns[n] = ns[n];
            }
        }
        return nns;
    };
    var processLeaf = function(lname, child, ns) {
        var body = "";
        if (child instanceof Array) {
            for (var i = 0; i < child.length; i++) {
                body += processLeaf(lname, child[i], cloneNS(ns));
            }
            return body;
        } else if (typeof child === "object") {
            var el = "<" + lname;
            var attributes = "";
            var text = "";
            if (child["@xmlns"]) {
                var xmlns = child["@xmlns"];
                for (var prefix in xmlns) {
                    if (xmlns.hasOwnProperty(prefix)) {
                        if (prefix === "$") {
                            if (ns[prefix] !== xmlns[prefix]) {
                                attributes += " " + "xmlns=\"" + xmlns[prefix] + "\"";
                                ns[prefix] = xmlns[prefix];
                            }
                        } else if (!ns[prefix] || (ns[prefix] !== xmlns[prefix])) {
                            attributes += " xmlns:" + prefix + "=\"" + xmlns[prefix] + "\"";
                            ns[prefix] = xmlns[prefix];
                        }
                    }
                }
            }
            for (var key in child) {
                if (child.hasOwnProperty(key) && key !== "@xmlns") {
                    var obj = child[key];
                    if (key === "$") {
                        text += obj;
                    } else if (key.indexOf("@") === 0) {
                        attributes += " " + key.substring(1) + "=\"" + obj + "\"";
                    } else {
                        body += processLeaf(key, obj, cloneNS(ns));
                    }
                }
            }
            body = text + body;
            return (body !== "") ? el + attributes + ">" + body + "</" + lname + ">" : el + attributes + "/>"
        }
    };
    for (var lname in json) {
        if (json.hasOwnProperty(lname) && lname.indexOf("@") == -1) {
            return processLeaf(lname, json[lname], {});
        }
    }
    return null;
}

Tuesday, February 22, 2011

Parse XML String into DOM with Javascript

You can use following function to convert any XML string into a DOM object from a browser.
function parseXML(xml) {
    xml = xml.replace(/^[\s\n\r\t]*[<][\?][xml][^<^>]*[\?][>]/, "");
    var doc;
    if (window.ActiveXObject) {
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.async = false;
        doc.loadXML(xml);
    } else
        doc = (new DOMParser()).parseFromString(xml, "application/xml");
    return doc;
}

Online XML to JSON Converter using Badgerfish Notation

I have hosted an online XML to JSON converter at http://gogooog.com. It has been implemented purely with Javascript. You can read about the xml to badgerfish conversion at http://ruchirawageesha.blogspot.com/2011/01/xml-to-badgerfish-converter-in.html.

Friday, January 28, 2011

XML to BadgerFish Conversion in Javascript

Recently I came across the need of converting an xml into a JSON format. There I used BadgerFish notation to transform the xml into JSON.

You can use following Javascript function to convert any DOM node into the relevant BadgerFish notation. You can convert any XML string into a DOM object using method described at Parse XML String into DOM with Javascript

Please find the hosted version of XML to Badgerfish converter at gogooog.com
function xml2bf(node) {
    var json = {};
    var cloneNS = function(ns) {
        var nns = {};
        for (var n in ns) {
            if (ns.hasOwnProperty(n)) {
                nns[n] = ns[n];
            }
        }
        return nns;
    };
    var process = function (node, obj, ns) {
        if (node.nodeType === 3) {
            if (!node.nodeValue.match(/[\S]+/)) return;
            if (obj["$"] instanceof Array) {
                obj["$"].push(node.nodeValue);
            } else if (obj["$"] instanceof Object) {
                obj["$"] = [obj["$"], node.nodeValue];
            } else {
                obj["$"] = node.nodeValue;
            }
        } else if (node.nodeType === 1) {
            var p = {};
            var nodeName = node.nodeName;
            for (var i = 0; node.attributes && i < node.attributes.length; i++) {
                var attr = node.attributes[i];
                var name = attr.nodeName;
                var value = attr.nodeValue;
                if (name === "xmlns") {
                    ns["$"] = value;
                } else if (name.indexOf("xmlns:") === 0) {
                    ns[name.substr(name.indexOf(":") + 1)] = value;
                } else {
                    p["@" + name] = value;
                }
            }
            for (var prefix in ns) {
                if (ns.hasOwnProperty(prefix)) {
                    p["@xmlns"] = p["@xmlns"] || {};
                    p["@xmlns"][prefix] = ns[prefix];
                }
            }
            if (obj[nodeName] instanceof Array) {
                obj[nodeName].push(p);
            } else if (obj[nodeName] instanceof Object) {
                obj[nodeName] = [obj[nodeName], p];
            } else {
                obj[nodeName] = p;
            }
            for (var j = 0; j < node.childNodes.length; j++) {
                process(node.childNodes[j], p, cloneNS(ns));
            }
        } else if (node.nodeType === 9) {
            for (var k = 0; k < node.childNodes.length; k++) {
                process(node.childNodes[k], obj, cloneNS(ns));
            }
        }
    };
    process(node, json, {});
    return json;
}