XML to JSON Conversion
Xml to JSON convertion as plain json object without node's attribute
by dshilkret
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js"></script>
JavaScript
// Changes XML to JSON
function xmlToJson(xml, ignoreAttr) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (!ignoreAttr && xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
if((xml.hasChildNodes()
&& Array.prototype.filter.call(xml.childNodes, function(node) { return node.nodeType == 3; }).length === 1)
|| (!xml.hasChildNodes() && xml.childNodes.length ===0)) {
obj = xml.textContent;
return obj;
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item, ignoreAttr);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item, ignoreAttr));
}
}
}
return obj;
};
var xml = $.parseXML('<statuses><status id="one"><id>1</id><text>Hello!</text></status></statuses>');
xml = $.parseXML('<ServicePointValidationResponse xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PlatformServices.Models.Admin"><FileContentType>ServicePointID</FileContentType><InvalidAttributes /><ValidServicePoints><ServicePointDetailDto><AccountName i:nil="true" /><AccountNumber i:nil="true" /><AccountType i:nil="true"...