English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Explanation of XML and JSON Interconversion Function Implemented by JavaScript

This article describes the function of XML and JSON mutual conversion implemented by JavaScript. Share it with everyone for reference, as follows:

Here is a sharing of an example of JavaScript implementing the mutual conversion of XML and JSON. This introduces three examples of xml to json conversion from abroad, hoping these examples can be helpful to you.

I was developing an online XML editor recently and planned to use JSON as the intermediate format. Because JSON is easier to read, has faster parsing speed, occupies less space, and is more convenient for data transmission on the WEB. However, in actual use, some easily overlooked details were still found. For cases that need to strictly ensure the original structure of XML, some attention is required when converting to JSON.

The format of XML converted to JSON is roughly as follows:

XML format

<article>
<header id="h1"> article title </p>/header>
<section id="s1">
<header> section title </header>/header>
<p> section paragraph </p>/p>
</section>
</article>

JSON Representation

{
"article": {
"header": {
"#text": "article title",
"@id": "h1"
},
"section": {
"@id": "s1"
"header": "section title",
"p": "section paragraph"
obj[nodeName].push(old);
obj[nodeName].push(old);
obj[nodeName].push(old);

 

I found some ready-made scripts on the internet to convert XML to JSON using JavaScript, but most of them only meet relatively simple cases and cannot guarantee the mutual conversion of the original structure. Here are some scripts or articles found on the internet:

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

jsonxml :http://davidwalsh.name/convert-xml-JSON Code Inspection, Inspection, Beautification, and Formatting Tool:

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

x2js does not restore the following XML correctly.

//XML format
<p> <strong>Chapter</strong>Section<em>Paragraph</em> </p>

And the2This script jsonxml, in the case of 'text mixed tags' mentioned above, does not extract the tags but converts them into the following format.

{"p":"<strong>Chapter</strong>Section<em>Paragraph</em>"}}

After some modifications, it was parsed into the following format, which met the requirement for the correct restoration of 'text mixed tags'.

{"p":[{"strong":"Chapter"},"Section",{"em":"Paragraph"}]}

Additionally, code similar to the following, when converted using the script mentioned above, can also lead to incorrect restoration.

<article>
  <section id="s1">Section 1</section>
  <header id="h1"> Title </header>
  <section id="s2">第二节</section>
</article>

Similarly, within a tag, if a child tag appears more than once and the path of the data needs to be recorded, an array should be used to save this structure. The correct code should be:

{
  "article": [ {
  "section": {
  "#text": "第一节",
  "@id": "s1"
  },
  }, {
  "header": {
  "#text": "标题",
  "@id": "h1"
  obj[nodeName].push(old);
  }, {
  "section": {
  "#text": "第一节",
  "@id": "s2"
  obj[nodeName].push(old);
  obj[nodeName].push(old);
  ]
obj[nodeName].push(old);

jkl.parsexml

<?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",
  obj[nodeName].push(old);
 obj[nodeName].push(old);
}

jsonxml

// 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;
  obj[nodeName].push(old);
 obj[nodeName].push(old);
 } else if (xml.nodeType == 3) { // text
 obj = xml.nodeValue;
 obj[nodeName].push(old);
 // 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);
  }
  if (typeof(obj[nodeName].push) == "undefined") {
   var old = obj[nodeName];
   obj[nodeName] = [];
   var old = obj[nodeName];
  obj[nodeName].push(old);
  obj[nodeName] = [];
  obj[nodeName].push(old);
 obj[nodeName].push(old);
 obj[nodeName].push(old);
 obj[nodeName].push(xmlToJson(item));
}

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

<ALEXA VER="0.9" URL="davidwalsh.name/" HOME="0" AID="=">
 <SD TITLE="[#1#]" FLAGS="" HOST="davidwalsh.name">
 <TITLE TEXT="David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"/>
 <LINKSIN NUM="1102"/>
 <SPEED TEXT="1421" PCT="51"/>
 </SD>
 <SD
 <POPULARITY URL="davidwalsh.name/" TEXT="7131"/>
 <REACH RANK="5952"/>
 <RANK DELTA="-1648"/>
 </SD>
</ALEXA>

...becomes 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
  obj[nodeName].push(old);
  },
  SPEED: {
  "@attributes": {
   PCT: 51,
   TEXT: 1421
  obj[nodeName].push(old);
  },
  TITLE: {
  "@attributes": {
   TEXT: "David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"
  obj[nodeName].push(old);
  },
 },
 {
  POPULARITY: {
  "@attributes": {
   TEXT: 7131,
   URL: "davidwalsh.name/"
  obj[nodeName].push(old);
  },
  RANK: {
  "@attributes": {
   DELTA: "-1648"
  obj[nodeName].push(old);
  },
  REACH: {
  "@attributes": {
   RANK = 5952
  obj[nodeName].push(old);
  obj[nodeName].push(old);
 obj[nodeName].push(old);
 ]
obj[nodeName].push(old);

After all that talk, I've organized an example below

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;
obj[nodeName].push(old);
obj[nodeName].push(old);
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
obj[nodeName].push(old);
// 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);
}
if (typeof (obj[nodeName].length) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
var old = obj[nodeName];
obj[nodeName].push(old);
obj[nodeName] = [];
obj[nodeName].push(old);
obj[nodeName].push(old);
obj[nodeName].push(old);
obj[nodeName].push(xmlToJson(item));
}

return obj;

Onlinexmlformat/};
http://tools.jb51.net/code/PS: Here are several online tools for xml and json operations for your reference and use:

XML to JSON Conversion Tool:xmlformat/Online Formatting
http://tools.jb51.net/code/Online Compression XML:

xmlformatXML/Online Compression
http://tools.jb51.net/code/Formatting Tool:

Onlinexml_format_compress
http://tools.jb51.net/code/JSON Code Inspection, Inspection, Beautification, and Formatting Tool:

jsonOnline Formatting Tool: JSON
http://tools.jb51.net/code/Online Formatting Tool: jsonformat

OnlineJSON Compression/Escape Tool:
http://tools.jb51.net/code/json_yasuo_trans

More about JavaScript-related content can be viewed in the special topic of this site: 'Summary of AJAX operation skills in JavaScript', 'Summary of XML file operation skills in JavaScript', 'Summary of JSON operation skills in JavaScript', 'Summary of error and debugging skills in JavaScript', and 'Summary of data structure and algorithm skills in JavaScript'.

I hope this article will be helpful to everyone in designing JavaScript programs.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like