当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript实现的XML与JSON互转功能详解

JavaScript实现的XML与JSON互转功能详解

2019年03月25日  | 移动技术网IT编程  | 我要评论
本文实例讲述了javascript实现的xml与json互转功能。分享给大家供大家参考,具体如下: 这里来分享一个关于javascript实现xml与json互转例子,这

本文实例讲述了javascript实现的xml与json互转功能。分享给大家供大家参考,具体如下:

这里来分享一个关于javascript实现xml与json互转例子,这里面介绍了国外的三款xml转json的例子,希望这些例子能给你带来帮助。

最近在开发在线xml编辑器,打算使用json做为中间格式。因为json相对于xml,有着容易阅读、解析速度快、占用空间小等优点,更易于在web上传递数据。但在实际使用中还是发现了一些易于忽略的细节,对于需要严格保证xml原始结构的情况,在转换成json时需要一些注意。

xml转换成json的格式大概如下:

xml形式

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

json表现形式

{
"article": {
"header": {
"#text": "文章标题",
"@id": "h1"
},
"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="h1"> 标题 </header>
  <section id="s2">第二节</section>
</article>

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

{
  "article": [ {
  "section": {
  "#text": "第一节",
  "@id": "s1"
  },
  }, {
  "header": {
  "#text": "标题",
  "@id": "h1"
  }
  }, {
  "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;
};

ps:这里再为大家提供几款关于xml与json操作的在线工具供大家参考使用:

在线xml/json互相转换工具:

在线格式化xml/在线压缩xml

xml在线压缩/格式化工具:

在线json代码检验、检验、美化、格式化工具:

json在线格式化工具:

在线json压缩/转义工具:

更多关于javascript相关内容可查看本站专题:《javascript中ajax操作技巧总结》、《javascript操作xml文件技巧总结》、《javascript中json操作技巧总结》、《javascript错误与调试技巧总结》及《javascript数据结构与算法技巧总结

希望本文所述对大家javascript程序设计有所帮助。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网