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

2025-09-07


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

                                js瀹炵幇xml杞琷son                       <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js">    <script type="text/javascript">// Converts XML to JSON// from: http://coursesweb.net/javascript/convert-xml-json-javascript_s2function 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 '\t\r\n', 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(/"",[\n\t\r\s]+""[,]*/g, '').replace(/(\n[\t\s\r]*\n)/g, '').replace(/[\s\t]{2,}""[,]{0,1}/g, '').replace(/"[\s\t]{1,}"[,]{0,1}/g, '').replace(/\[[\t\s]*\]/g, '""');    return (rejsn.indexOf('"parsererror": {') == -1) ? rejsn : 'Invalid XML format';  }};// creates object instantce of XMLtoJSONvar xml2json = new XMLtoJSON();<script type="text/javascript">  var xmlstr = `      CoursesWeb: php, mysql, html, css, javascript, ajax, jquery, actionscript, flash        4578        5777        6667  `;// gets JSON object from a string with xml contentvar objson = xml2json.fromStr(xmlstr);console.log(objson);// gets JSON string from a string with xml contentvar strjson = xml2json.fromStr(xmlstr, 'string');console.log(strjson);              

标签: xml转json

本文地址:https://www.lifejia.cn/news/209975.html

免责声明:本站内容仅用于学习参考,信息和图片素材来源于互联网,如内容侵权与违规,请联系我们进行删除,我们将在三个工作日内处理。联系邮箱:cloudinto#qq.com(把#换成@)