How to realize mutual conversion between XML and JSON in JS

  • 2021-07-04 17:53:26
  • OfStack

In the development, we sometimes encounter the mutual conversion between XML and JSON, which is required to be used in JS. I found a lot on the Internet, but every one is easy to use, either lacking arms and legs, or the words are not satisfactory, which is too unreasonable. I decisively realize one by myself.

Comparison between JSON and XML

1. Introduction to Definitions

(1). XML definition

Extensible Markup Language (Extensible Markup Language, XML), which is used to mark electronic documents to make them have structural markup language, can be used to mark data and define data types, is a source language that allows users to define their own markup language. XML uses DTD (document type definition) document type definitions to organize data; Format 1, cross-platform and language, has long been recognized as a standard in the industry.
XML is a subset of the Standard Universal Markup Language (SGML) and is well suited for Web transmissions. XML provides a unified approach to describing and exchanging structured data independent of applications or vendors.

(2). JSON definition

JSON (JavaScript Object Notation) is a lightweight data exchange format with good readability and easy to write quickly. Data can be exchanged between different platforms. JSON adopts a highly compatible and completely independent text format, and also has the behavior similar to C language habits (including C, C + +, C #, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language.
JSON is based on a subset of JavaScript Programming Language, Standard ECMA-262 3rd Edition-December 1999.

2. Advantages and disadvantages of XML and JSON

(1). Advantages and disadvantages of XML

< 1 > Advantages of XML
A. Format 1, conforming to the standard;
B. It is easy to interact with other systems remotely, and data sharing is convenient.

< 2 > Disadvantages of XML
A. XML file is huge, file format is complex, and transmission takes up bandwidth;
B. Both server and client need to spend a lot of code to parse XML, which makes the server and client code extremely complex and difficult to maintain;
C. The way of analyzing XML between different browsers on the client side is not 1, and a lot of code needs to be written repeatedly;
D. Server-side and client-side parsing XML takes more resources and time.

(2). Advantages and disadvantages of JSON

< 1 > . Advantages of JSON:
A. The data format is simple, easy to read and write, the format is compressed, small bandwidth;

B. Easy to parse, the client JavaScript can simply through eval () JSON data read;

C. supports many languages, including ActionScript, C, C #, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby and other server-side languages, which is convenient for server-side parsing;

D. In the world of PHP, PHP-JSON and JSON-PHP have appeared, which are called directly by the serialized program of PHP, and the objects and arrays on the server side of PHP can directly generate JSON format, which is convenient for the client to access and extract;

E. Because JSON format can be directly used for server-side code, it greatly simplifies the code development of server-side and client-side, and the task is unchanged and easy to maintain.

< 2 > . Disadvantages of JSON

A. There is no XML format so popular and popular, and there is no XML so universal;

B. JSON format is still in the initial stage of popularization in Web Service.

Conversion between XML and JSON in Javascript

Let's look at the invocation example first:


<viewport id="menuPane" layout="border">
    <panel region="center" border="0" layout="border">
        <tbar>
            <toolbar text="XXXX">
                <menu>
                    <text text="11">
                    </text>
                    <text text="22">
                    </text>
                    <text text="33">
                    </text>
                </menu>
            </toolbar>
            <toolbar text="XXXX">
                <menu>
                    <text text="44">
                    </text>
                    <text text="55">
                    </text>
                    <menu>
                        <text text="6 6">
                        </text>
                    </menu>
                    <text text="77">
                    </text>
                </menu>
            </toolbar>
        </tbar>
    </panel>
</viewport>
var xmlParser = new XmlToJson();
var json = xmlParser.parse(xml);
console.log( JSON.stringify(json) );
var jsonParser = new JsonToXml();
var xml = jsonParser.parse(json);
console.log( xml );

XML to JSON:


function XmlToJson() {
}
XmlToJson.prototype.setXml = function(xml) {
    if(xml && typeof xml == "string") {
        this.xml = document.createElement("div");
        this.xml.innerHTML = xml;
        this.xml = this.xml.getElementsByTagName("*")[0];
    }
    else if(typeof xml == "object"){
        this.xml = xml;
    }
};
XmlToJson.prototype.getXml = function() {
    return this.xml;
};
XmlToJson.prototype.parse = function(xml) {
    this.setXml(xml);
    return this.convert(this.xml);
};
XmlToJson.prototype.convert = function(xml) {
    if (xml.nodeType != 1) {
        return null;
    }
    var obj = {};
    obj.xtype = xml.nodeName.toLowerCase();
    var nodeValue = (xml.textContent || "").replace(/(\r|\n)/g, "").replace(/^\s+|\s+$/g, "");
   
    if(nodeValue && xml.childNodes.length == 1) {
        obj.text = nodeValue;
    }
    if (xml.attributes.length > 0) {
        for (var j = 0; j < xml.attributes.length; j++) {
            var attribute = xml.attributes.item(j);
            obj[attribute.nodeName] = attribute.nodeValue;
        }
    }
    if (xml.childNodes.length > 0) {
        var items = [];
        for(var i = 0; i < xml.childNodes.length; i++) {
            var node = xml.childNodes.item(i);
            var item = this.convert(node);
            if(item) {
                items.push(item);
            }
        }
        if(items.length > 0) {
            obj.items = items;
        }
    }
    return obj;
};

JSON to XML:


function JsonToXml() {
 this.result = [];
}
JsonToXml.prototype.spacialChars = ["&","<",">","\"","'"];
JsonToXml.prototype.validChars = ["&","<",">",""","'"];
JsonToXml.prototype.toString = function(){
 return this.result.join("");
};
JsonToXml.prototype.replaceSpecialChar = function(s){
    for(var i=0;i<this.spacialChars.length;i++){
        s=s.replace(new RegExp(this.spacialChars[i],"g"),this.validChars[i]);
    }
    return s;
};
JsonToXml.prototype.appendText = function(s){
    s = this.replaceSpecialChar(s);
    this.result.push(s);
};
JsonToXml.prototype.appendAttr = function(key, value){
    this.result.push(" "+ key +"=\""+ value +"\"");
};
JsonToXml.prototype.appendFlagBeginS = function(s){
 this.result.push("<"+s);
};
JsonToXml.prototype.appendFlagBeginE = function(){
 this.result.push(">");
};
JsonToXml.prototype.appendFlagEnd = function(s){
 this.result.push("</"+s+">");
};
JsonToXml.prototype.parse = function(json){
 this.convert(json);
 return this.toString();
};
JsonToXml.prototype.convert = function(obj) {
 var nodeName = obj.xtype || "item";
 this.appendFlagBeginS(nodeName);
 var arrayMap = {};
 for(var key in obj) {
  var item = obj[key];
  if(key == "xtype") {
   continue;
  }
  if(item.constructor == String) {
   this.appendAttr(key, item);
  }
  if(item.constructor == Array) {
   arrayMap[key] = item;
  }
 }
 this.appendFlagBeginE();
 for(var key in arrayMap) {
  var items = arrayMap[key];
  for(var i=0;i<items.length;i++) {
   this.convert(items[i]);
  }
 }
 this.appendFlagEnd(nodeName);
};

The above is arranged for everyone to realize the conversion between XML and JSON in Javascript. I hope this article is helpful for everyone to learn javascript.

Friends who are interested in the conversion between XML and JSON can also refer to online tools:

Online XML/JSON Interconversion Tool

Online XML Formatting/Compression Tool


Related articles: