How to implement mutual transform XML and Json_jquery in JS

Source: Internet
Author: User
Tags php server

Development sometimes encounter XML and JSON conversion, requirements in the use of JS, the Internet to find a lot of, unexpectedly every good, or lack of arms and legs, or the wrong, too no justice, decisive himself to achieve one.

Comparison of the differences between JSON and XML

1. Introduction to the definition

(1). XML definition

The Extensible Markup Language (extensible Markup Language, XML), which is used to mark an electronic file with a structured markup language, can be used to mark data, define data types, and is a source language that allows users to define their own markup language. XML organizes data using the DTD (document type definition) document types definition, which has long been recognized by the industry as a standard for consistency, cross-platform, and language.
XML is a subset of standard Universal Markup Language (SGML) that is ideal for Web transport. XML provides a uniform way to describe and exchange structured data that is independent of applications or vendors.

(2). JSON definition

JSON (JavaScript Object notation) a lightweight data interchange format with good readability and fast-coding features. Data exchange can be made between different platforms. JSON is highly compatible, completely independent of the language text format, but also has similar C-language habits (including C, C + +, C #, Java, JavaScript, Perl, Python, etc.) the behavior of the system. These features make JSON an ideal data exchange language.
JSON is based on JavaScript programming Language, Standard ECMA-262 a subset of 3rd Edition-december 1999.

2.XML and JSON pros and cons

(1). Advantages and disadvantages of XML

<1>. The benefits of XML
A. Format uniformity and compliance with standards;
B. Easy to interact with other systems remotely, and data sharing is more convenient.

<2>. Disadvantages of XML
A.xml file is large, the file format is complex, the transmission occupies the bandwidth;
B. Both the server side and the client require a large amount of code to parse the XML, causing the server-side and client code to become unusually complex and difficult to maintain;
C. The client is inconsistent in parsing XML between different browsers and needs to write a lot of code repeatedly;
D. Server-side and client-resolution XML cost more resources and time.

(2). The pros and cons of JSON

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

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

C. Support multiple languages, including ActionScript, C, C #, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby and other server-side languages, easy server-side resolution;

D. In the PHP world, there have been Php-json and json-php appeared, biased in PHP after the serialization of the program direct call, PHP server-side objects, arrays, etc. can directly generate JSON format, easy access to the client to extract;

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

<2>. The disadvantage of JSON

A. There is no XML format so popularized and popular, and not as universal as XML;

The B.json format is currently promoted in the Web service and is still in its infancy.

Implementing XML and JSON conversion in JavaScript

First look at the invocation example:

Copy Code code as follows:

<viewport id= "Menupane" layout= "Border" >
<panel region= "center" border= "0" layout= "border" >
<tbar>
<toolbar text= "XXXX" >
<menu>
<text text= "One" >
</text>
<text text= ">"
</text>
<text text= ">"
</text>
</menu>
</toolbar>
<toolbar text= "XXXX" >
<menu>
<text text= ">"
</text>
<text text= ">"
</text>
<menu>
<text text= "6 6" >
</text>
</menu>
<text text= ">"
</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);

Convert XML to JSON:

Copy Code code as follows:

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 is converted to XML:

Copy Code code as follows:

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 for you to organize the implementation of XML and JSON conversion in JavaScript, I hope this article will help you learn JavaScript.

Friends who are interested in converting XML and JSON can also refer to online tools:

On-line Xml/json Mutual conversion tool

Online XML format/compression tools

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.