Javascript Course

Test the XML to JSON Converter online

The script presented in this page is a JavaScript object that can be used to convert XML content to JSON object, or to JSON string.
- You can copy and use the code presented bellow, or click to Download the XML to JSON Converter (the arhive contains examples of usage).
• This object can be used in all modern browsers (Mozilla Firefox, Google Chrome, Opera, IE 9+).

Code of XML to JSON converter

// Converts XML to JSON
// from: https://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 '\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 XMLtoJSON
var xml2json = new XMLtoJSON();
- This object has two methods to use:

Usage

1. Copy the code above and add it into a ".js" file named "xml2json.js" (or use the file from the archive from the Download link above).
2. In the web page in which you want to use the XML to JSON converter, add this code:
<script type="text/javascript" src="xml2json.js"></script>
3.a - If you want to convert an XML content from an external ".xml" file, call the xml2json.fromFile('file.xml') method in your JavaScript script. It returns the JSON object. If you want to convert the XML to JSON String, add a second argument with the value of "string".
Example:
// gets JSON object from an external xml file
var objson = xml2json.fromFile('file.xml');

// gets JSON string from an external xml file
var strjson = xml2json.fromFile('file.xml', 'string');
3.b - If you want to convert an XML content stored into a String, call the xml2json.fromStr('string with xml') method in your JavaScript script. It returns the JSON object. If you want to convert the XML to JSON String, add a second argument with the value of "string".
Example:
var xmlstr = 'string with xml content';

// gets JSON object from a string with xml content
var objson = xml2json.fromStr(xmlstr);

// gets JSON string from a string with xml content
var strjson = xml2json.fromStr(xmlstr, 'string');

Test the XML to JSON Converter online

- Click Clear button, add your valid XML, and click "Convert to JSON".

 
JSON object:
- To create this object, I used the function from Convert XML-DOM to JSON object
- The script is Free, you can use it, modify, and publish it freely.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which attribute is used in <a> tag for the address of the link?
src href rel
<a href="http://coursesweb.net/" title="CoursesWeb.net">CoursesWeb.net</a>
Which CSS property sets the type of the text font?
font-family text-decoration font-size
h2 {
  font-family:"Calibri",sans-serif;
}
What instruction selects all the <div> tags with class="cls"?
querySelector("div.cls") getElementsByTagName("div") querySelectorAll("div.cls")
var elm_list = document.querySelectorAll("div.cls");
var nr_elms = elm_list.length;       // number of selected items
alert(nr_elms);
Indicate the function that can be used to get the sum of values in an array.
array_sum() array_diff() array_shift()
$arr =[1, 2, 3, 4);
$arr_sum = array_sum($arr);
echo $arr_sum;       // 10
Convert XML to JSON in JavaScript

Last accessed pages

  1. SSEP - Site Search Engine PHP-Ajax (11402)
  2. PHP Unzipper - Extract Zip, Rar Archives (31758)
  3. querySelector and querySelectorAll (30029)
  4. Moving html element to a random direction (5088)
  5. TV-Screen shape with CSS (4293)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (347)
  2. Read Excel file data in PHP - PhpExcelReader (131)
  3. The Four Agreements (98)
  4. PHP Unzipper - Extract Zip, Rar Archives (97)
  5. The Mastery of Love (94)