使用JavaScript怎么将XML与JSON进行转换

发布时间:2021-02-23 15:25:38 作者:戴恩恩
来源:亿速云 阅读:211

本文章向大家介绍使用JavaScript怎么将XML与JSON进行转换的基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

JavaScript是什么

JavaScript是一种直译式的脚本语言,其解释器被称为JavaScript引擎,是浏览器的一部分,JavaScript是被广泛用于客户端的脚本语言,最早是在HTML网页上使用,用来给HTML网页增加动态功能。

XML转换成JSON的格式大概如下:

XML形式

<article>
<header id="h2"> 文章标题 </header>
<section id="s1">
<header> 章节标题 </header>
<p> 章节段落 </p>
</section>
</article>

JSON表现形式

{
"article": {
"header": {
"#text": "文章标题",
"@id": "h2"
},
"section": {
"@id": "s1",
"header": "章节标题",
"p": "章节段落"
}
}
}

用Js将XML转换成JSON的脚本,在网上找了一些现成的脚本,但大都只满足比较简单的情况,都不可以完成保证原始结构的互转。下面是从网上找到的一些脚本或者文章:

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不会将下面的XML正确还原。

//XML形式
<p> <strong>章节</strong>段<em>落</em> </p>

而第2个脚本jsonxml,在上面这种“文本混合标签”的情况下,没有将标签提取出来,而是转换成了下面这种格式。

{"p":"<strong>章节</strong>段<em>落</em>"}}

之后我做了些改动,将它解析成如下格式后,满足了“文本混合标签”可正确还原的情况。

{"p":[{"strong":"章节"},"段",{"em":"落"}]}

另外,形如下面的代码,使用上文提到的脚本进行转换,也会导致无法正确还原的情况。

<article>
  <section id="s1">第一节</section>
  <header id="h2"> 标题 </header>
  <section id="s2">第二节</section>
</article>

同样,在一个标签内,它的子标签出现了大于一次,如果需要记录数据的路径,应该使用数组来保存这个结构。正确的代码应该是:

{
  "article": [ {
  "section": {
  "#text": "第一节",
  "@id": "s1"
  },
  }, {
  "header": {
  "#text": "标题",
  "@id": "h2"
  }
  }, {
  "section": {
  "#text": "第一节",
  "@id": "s2"
  }
  }
  ]
}

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",
  }
 }
};

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;
  }
 }
 } 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 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="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="51"/>
 </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
  }
  }
 }
 ]
}

说了半天下面整理了一个例子

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;
};

以上就是小编为大家带来的使用JavaScript怎么将XML与JSON进行转换的全部内容了,希望大家多多支持亿速云!

推荐阅读:
  1. XML与JSON如何进行相互转换
  2. 如何使用xlst将xml转换html

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javascript xml json

上一篇:使用JavaScript怎么编写一个256色转灰度图功能

下一篇:使用JavaScript怎么将xml对象转换为Json对象

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》