JavaScript implements XML and JSON interchange code

Source: Internet
Author: User
Tags mixed mootools

The recent development of an online XML editor is intended to use JSON as an intermediate format. Because JSON is easier to read, parse faster, and occupy less space than XML, it is easier to pass data on the web. In practice, however, there are some easy to ignore details that require some attention when converting to JSON to ensure that the original structure of the XML is strictly guaranteed.

The format for converting XML into JSON is probably as follows:

The code is as follows Copy Code

    //xml form
    <article>
        <section id= "S1"
        <p> Chapter paragraph </p>
    </section>
    </ Article>
   //json representation
    {
    "article": {
 & nbsp;  "header": {
    "#text": "article title",
    "@id": "H1"
    },
    "section": {
    "@id": "S1",
    "header": "chapter title ",
   " P ":" chapter paragraph "
   }
   }
   }

Use JS to convert XML into JSON script, find some ready-made scripts on the Internet, but most of them only meet the relatively simple situation, can not complete the original structure to ensure the mutual turn. Here are some of the scripts or articles found online:

x2js:https://code.google.com/p/x2js/

Jsonxml:http://davidwalsh.name/convert-xml-json

JKL. Parsexml:http://www.kawa.net/works/js/jkl/parsexml-e.html

X2JS will not restore the following XML correctly.

The code is as follows Copy Code

XML form
<p> <strong> Chapters </strong> segment <em> down </em> </p>

The 2nd script Jsonxml, in the case of the "text mixed tag" above, did not extract the label, but instead converted it to the following format.

The code is as follows Copy Code

{"P": "<strong> Chapter </strong> paragraph <em> Fall </em>"}}

After I made some changes, it resolves to the following format, satisfies the "text mixed label" can be restored correctly.

The code is as follows Copy Code

{"P": [{"Strong": "chapter"}, "paragraph", {"em": "Fall"}]}

In addition, the following code, using the script mentioned above, can also cause a situation that cannot be restored correctly.

The code is as follows Copy Code

<article>
<section id= "S1" > first section </section>
<section id= "s2" > section II </section>
</article>

Similarly, within a label, its child labels appear more than once, and if you need to record the path of the data, you should use an array to save the structure. The correct code should be:

The code is as follows Copy Code

{
"article": [{
"section": {
"#text": "The first section",
"@id": "S1"
},
}, {
"Header": {
"#text": "title",
"@id": "H1"
}
}, {
"section": {
"#text": "The first section",
"@id": "S2"
}
}
]
}


Jkl.parsexml

The code is as follows Copy Code

SAMPLE XML Source:xml

<?xml version= "1.0" encoding= "UTF-8" standalone= "yes"?>
<items>
<item>
<zip_cd>10036</zip_cd>
<us_state>NY</us_state>
<us_city>new york</us_city>
<us_dist>Broadway</us_dist>
</item>
</items>

SAMPLE SCRIPT:

<script type= "Text/javascript" src= "Jkl-parsexml.js" ></script>
<script><!--
var url = "Zip-e.xml";
var xml = new JKL. Parsexml (URL);
var data = Xml.parse ();
document.write (data["items"] ["Item"] ["us_state"]);
document.write (data.items.item.us_state);
--></script>

OUTPUT JSON:

{
Items: {
Item: {
ZIP_CD: "1000001"
Us_state: "NY",
Us_city: "New York",
Us_dist: "Broadway",
}
}
};

Jsonxml

The code is as follows Copy Code

Changes XML to JSON
function Xmltojson (XML) {

Create the Return object
var obj = {};

if (Xml.nodetype = = 1) {//Element
Do attributes
if (Xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; J < Xml.attributes.length; J + +) {
var attribute = Xml.attributes.item (j);
obj["@attributes"][attribute.nodename] = Attribute.nodevalue;
}
}
else if (Xml.nodetype = 3) {//text
obj = Xml.nodevalue;
}

 //do children
 if (Xml.haschildnodes ()) {
  for (var i = 0; i < xml.childNodes.length; i++) {
   var item = Xml.childNodes.item (i);
   var nodename = item.nodename;
   if (typeof (Obj[nodename]) = = "undefined") {
    obj[nodename] = Xmltojson ( Item);
   } else {
    if (typeof (Obj[nodename].push) = = "undefined") {
      var old = Obj[nodename];
     obj[nodename] = [];
     obj[nodename].push (old);
    }
    obj[nodename].push (Xmltojson (item));
   }
  }
 }
 return obj;
};

The major change I needed to implement is using Attributes.item (j) instead of the attributes[j] that most of the scripts  I found used. With the This function, XML which looks like:

<alexa ver= "0.9" url= "davidwalsh.name/" home= "0" aid= "=" >
<SD title= "A" flags= "" host= "Davidwalsh.name" >
<title text= "David Walsh Blog:: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"/>
<linksin num= "1102"/>
<speed text= "1421" pct= "Wuyi"/>
</SD>
<SD>
<popularity url= "davidwalsh.name/" text= "7131"/>
<reach rank= "5952"/>
<rank delta= " -1648"/>
</SD>
</ALEXA>

... becomes workable a JavaScript object with the following structure:

{
"@attributes": {
AID: "=",
home:0,
URL: "davidwalsh.name/",
VER: "0.9",
},
SD = [
{
"@attributes": {
FLAGS: "",
HOST: "Davidwalsh.name",
Title:a
},
Linksin: {
"@attributes": {
num:1102
}
},
SPEED: {
"@attributes": {
Pct:51,
text:1421
}
},
TITLE: {
"@attributes": {
TEXT: "David Walsh Blog:: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else",
}
},
},
{
Popularity: {
"@attributes": {
text:7131,
URL: "davidwalsh.name/"
}
},
RANK: {
"@attributes": {
DELTA: "-1648"
}
},
Reach: {
"@attributes": {
RANK = 5952
}
}
}
]
}


For most of the night's records, please correct me if there are any wrong places.

For half a day, here's an example.

The code is as follows Copy Code

function Xmltojson (XML) {

Create the Return object
var obj = {};

if (Xml.nodetype = = 1) {//Element
Do attributes
if (Xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; J < Xml.attributes.length; J + +) {
var attribute = Xml.attributes.item (j);
obj["@attributes"][attribute.nodename] = Attribute.nodevalue;
}
}
else if (Xml.nodetype = 3) {//text
obj = Xml.nodevalue;
}

//Do children
if (Xml.haschildnodes ()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = Xml.childNodes.item (i);
var nodename = item.nodename;
if (typeof (Obj[nodename]) = = "undefined") {
Obj[nodename] = Xmltojson (item);
} else {
if (typeof (obj[nodename].length) = = "undefined") {
var old = Obj[nodename];
Obj[nodename] = [];
Obj[nodename].push (old);
}
Obj[nodename].push (Xmltojson (item));
}
}
}
return obj;
};

Related Article

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.