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 HTML5 tag is indicated to be used as container for menu with navigation links in Web site?
<section> <nav> <article>
<nav><ul>
 <li><a href="http://coursesweb.net/css/" title="CSS Course">CSS Course</a></li>
 <li><a href="http://www.marplo.net/jocuri/" title="Flash Games">Flash Games</a></li>
</ul></nav>
Which CSS property shifts an item horizontally to the left or right of where it was?
text-align clear float
.some_class {
  width: 30%;
  float: left;
}
Click on the Math object method which returns x, rounded downwards to the nearest integer.
Math.ceil(x) Math.abs(x) Math.floor(x)
var num = 12.34567;
num = Math.floor(num);
alert(num);       // 12
Indicate the PHP function which returns the number of characters in string.
mb_strlen() count() stristr()
$str = "string with utf-8 chars åèö";
$nrchr = mb_strlen($str);
echo $nrchr;        // 30
Convert XML to JSON in JavaScript

Last accessed pages

  1. this and target in JavaScript Events (1754)
  2. Working with MySQL Database (3047)
  3. Ajax-PHP File Manager (10130)
  4. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (137509)
  5. The Four Agreements (1608)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (198)
  2. Read Excel file data in PHP - PhpExcelReader (72)
  3. The Four Agreements (65)
  4. PHP Unzipper - Extract Zip, Rar Archives (63)
  5. Get and Modify content of an Iframe (49)
Chat
Chat or leave a message for the other users
Full screenInchide