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 tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Convert XML to JSON in JavaScript

Last accessed pages

  1. GraidleChart Create Graphic Charts (2008)
  2. Defining and using Functions in JS (1113)
  3. JavaScript Course - Free lessons (31656)
  4. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142523)
  5. Pencil and Pen Tools (2262)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (526)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (63)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)