首页 > web前端 > js教程 > 正文

代码分享js如何实现xml转json

零到壹度
发布: 2018-04-12 13:41:14
原创
2547人浏览过


本篇文章给大家分享的内容是js实现xml到json的转化,有着一定的参考价值,有需要的朋友可以参考一下

<!DOCTYPE html>      
<html>      
<head>      
    <meta charset="UTF-8">      
    <title>js瀹炵幇xml杞琷son</title>    
    <style type="text/css">    
        html,body{width:100%;height:100%;margin:0;}     
    </style>    
</head>      
<body>     
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>    
<script type="text/javascript">
// Converts XML to JSON
// from: http://coursesweb.net/javascript/convert-xml-json-javascript_s2
function XMLtoJSON() {
  var me = this;      // stores the object instantce
  // gets the content of an xml file and returns it in 
  me.fromFile = function(xml, rstr) {
    // Cretes a instantce of XMLHttpRequest object
    var xhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    // sets and sends the request for calling "xml"
    xhttp.open("GET", xml ,false);
    xhttp.send(null);
    // gets the JSON string
    var json_str = jsontoStr(setJsonObj(xhttp.responseXML));
    // sets and returns the JSON object, if "rstr" undefined (not passed), else, returns JSON string
    return (typeof(rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
  }
  // returns XML DOM from string with xml content
  me.fromStr = function(xml, rstr) {
    // for non IE browsers
    if(window.DOMParser) {
      var getxml = new DOMParser();
      var xmlDoc = getxml.parseFromString(xml,"text/xml");
    }
    else {
      // for Internet Explorer
      var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async = "false";
    }
    // gets the JSON string
    var json_str = jsontoStr(setJsonObj(xmlDoc));
    // sets and returns the JSON object, if "rstr" undefined (not passed), else, returns JSON string
    return (typeof(rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
  }
  // receives XML DOM object, returns converted JSON object
  var setJsonObj = function(xml) {
    var js_obj = {};
    if (xml.nodeType == 1) {
      if (xml.attributes.length > 0) {
        js_obj["@attributes"] = {};
        for (var j = 0; j < xml.attributes.length; j++) {
          var attribute = xml.attributes.item(j);
          js_obj["@attributes"][attribute.nodeName] = attribute.value;
        }
      }
    } else if (xml.nodeType == 3) {
      js_obj = xml.nodeValue;
    }            
    if (xml.hasChildNodes()) {
      for (var i = 0; i < xml.childNodes.length; i++) {
        var item = xml.childNodes.item(i);
        var nodeName = item.nodeName;
        if (typeof(js_obj[nodeName]) == "undefined") {
          js_obj[nodeName] = setJsonObj(item);
        } else {
          if (typeof(js_obj[nodeName].push) == "undefined") {
            var old = js_obj[nodeName];
            js_obj[nodeName] = [];
            js_obj[nodeName].push(old);
          }
          js_obj[nodeName].push(setJsonObj(item));
        }
      }
    }
    return js_obj;
  }
  // converts JSON object to string (human readablle).
  // Removes '	
', rows with multiples '""', multiple empty rows, '  "",', and "  ",; replace empty [] with ""
  var jsontoStr = function(js_obj) {
    var rejsn = JSON.stringify(js_obj, undefined, 2).replace(/(\t|\r|\n)/g, '').replace(/"",[
	
s]+""[,]*/g, '').replace(/(
[	s
]*
)/g, '').replace(/[s	]{2,}""[,]{0,1}/g, '').replace(/"[s	]{1,}"[,]{0,1}/g, '').replace(/[[	s]*]/g, '""');
    return (rejsn.indexOf('"parsererror": {') == -1) ? rejsn : 'Invalid XML format';
  }
};
// creates object instantce of XMLtoJSON
var xml2json = new XMLtoJSON();
</script>
<script type="text/javascript">  
var xmlstr = `<alexa ver="0.9" url="http://coursesweb.net/" home="0" aid="=">
  <sd title="a" host="coursesweb.net">
    <title>CoursesWeb: php, mysql, html, css, javascript, ajax, jquery, actionscript, flash</title>
    <linksin num="1102"/>
    <speed pct="51">4578</speed>
  </sd>
  <sd>
    <popularity>5777</popularity>
    <reach rank="5952"/>
    <rank url="http://coursesweb.net/">6667</rank>
  </sd>
</alexa>`;
// gets JSON object from a string with xml content
var objson = xml2json.fromStr(xmlstr);
console.log(objson);
// gets JSON string from a string with xml content
var strjson = xml2json.fromStr(xmlstr, 'string');
console.log(strjson);
</script>        
</body>      
</html>
登录后复制

以上就是代码分享js如何实现xml转json的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号