Andrew M
Andrew M

Reputation: 29

convert JSON object to XML using javascript

I want to convert a JSON object to a XML String and I can't figure a proper way to do it. I've found a neat little jQuery plugin called json2xml at https://gist.github.com/c4milo/3738875 but it doesn't escape the data.

How can I escape the data properly so that the browser's XML parser will work?

Upvotes: 2

Views: 18963

Answers (4)

user13032776
user13032776

Reputation: 1

you can use this function in your code to convert JSON to XML in js

var json2xml = function (o) {

            var tab = "\t";
            var toXml = function (v, name, ind) {
                var xml = "";
                if (v instanceof Array) {
                    for (var i = 0, n = v.length; i < n; i++)
                        xml += ind + toXml(v[i], name, ind + "\t") + "\n";
                }
                else if (typeof (v) == "object") {
                    var hasChild = false;
                    xml += ind + "<" + name;
                    for (var m in v) {
                        if (m.charAt(0) == "@")
                            xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
                        else
                            hasChild = true;
                    }
                    xml += hasChild ? ">" : "/>";
                    if (hasChild) {
                        for (var m in v) {
                            if (m == "#text")
                                xml += v[m];
                            else if (m == "#cdata")
                                xml += "<![CDATA[" + v[m] + "]]>";
                            else if (m.charAt(0) != "@")
                                xml += toXml(v[m], m, ind + "\t");
                        }
                        xml += (xml.charAt(xml.length - 1) == "\n" ? ind : "") + "</" + name + ">";
                    }
                }
                else {
                    xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
                }
            }
            return xml;
        };

you get XML DOM in return, which in return you need to serialize

so in the main

            var xmlDOM = json2xml(eval(jsonObj));
            var oSerializer = new XMLSerializer();
            var sXML = oSerializer.serializeToString(xmlDOM);

Upvotes: 0

user2174794
user2174794

Reputation: 59

You can use the external js available by google named x2js.js

You can see the demo over here.

jsFiddle Demo

Upvotes: 1

abdolence
abdolence

Reputation: 2416

You can try this small library http://code.google.com/p/x2js/

Upvotes: 2

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77454

There is no unique way of doing this. You should be using XML with a schema only, and JSON doesn't have such a schema. Any such transformation when done naively is likely to break.

Why don't you just use XML or JSON consequently?

Upvotes: 1

Related Questions