Home > Web Front-end > JS Tutorial > body text

Code sharing js how to convert xml to json

零到壹度
Release: 2018-04-12 13:41:14
Original
2440 people have browsed it


本篇文章给大家分享的内容是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) == &#39;undefined&#39;) ? 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) == &#39;undefined&#39;) ? 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 &#39;\t\r\n&#39;, rows with multiples &#39;""&#39;, multiple empty rows, &#39;  "",&#39;, and "  ",; replace empty [] with ""
  var jsontoStr = function(js_obj) {
    var rejsn = JSON.stringify(js_obj, undefined, 2).replace(/(\\t|\\r|\\n)/g, &#39;&#39;).replace(/"",[\n\t\r\s]+""[,]*/g, &#39;&#39;).replace(/(\n[\t\s\r]*\n)/g, &#39;&#39;).replace(/[\s\t]{2,}""[,]{0,1}/g, &#39;&#39;).replace(/"[\s\t]{1,}"[,]{0,1}/g, &#39;&#39;).replace(/\[[\t\s]*\]/g, &#39;""&#39;);
    return (rejsn.indexOf(&#39;"parsererror": {&#39;) == -1) ? rejsn : &#39;Invalid XML format&#39;;
  }
};
// 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, &#39;string&#39;);
console.log(strjson);
</script>        
</body>      
</html>
Copy after login

The above is the detailed content of Code sharing js how to convert xml to json. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!