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: 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 '\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 tag adds a new line into a paragraph?
<b> <br> <p>
First line ...<br>
Other line...
Which CSS property can be used to add space between letters?
text-size word-spacing letter-spacing
#id {
  letter-spacing: 2px;
}
What JavaScript function can be used to get access to HTML element with a specified ID?
getElementById() getElementsByTagName() createElement()
var elm = document.getElementById("theID");
var content = elm.innerHTML;
alert(content);
Click on the "echo" correct instruction.
echo "CoursesWeb.net" echo "CoursesWeb.net"; echo ""CoursesWeb.net";
echo "Address URL: http://CoursesWeb.net";
Convert XML to JSON in JavaScript

Last accessed pages

  1. Select in MySQL, Output results in HTML Table (1419)
  2. Golf Putt It In (739)
  3. Disable button and Enable it after specified time (5129)
  4. Flash Games - Free online Games (22975)
  5. Move image from an element /tag to another (1637)

Popular pages this month

  1. Qwop (3219)
  2. Get Attribute (ID, Class, Name, Title, Src) with jQuery (2547)
  3. Get the value of the selected /checked checkboxes in a form (1608)
  4. Insert, Select and Update NULL value in MySQL (1423)
  5. Add, Change, and Remove Attributes with jQuery (1301)