•
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:
- xml2json.fromFile('file.xml', ['string']) - converts the XML stored in external file. The first parameter is a string with the XML file address. The second parameter is Optional; if this argument, with the value of "string" is added, the method returns the JSON String, otherwise, returns the JSON object.
- xml2json.fromStr('xml string', ['string']) - converts the XML stored into a string. The first parameter is a string with the XML content. The second parameter is Optional; if this argument, with the value of "string" is added, the method returns the JSON String, otherwise, returns the JSON object.
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.