|  | 
| 4 | 4 |  * @example var json = $.xml2json(response); | 
| 5 | 5 |  */ | 
| 6 | 6 | (function() { | 
|  | 7 | + | 
|  | 8 | +	// default options based on https://github.com/Leonidas-from-XIV/node-xml2js | 
|  | 9 | +	var defaultOptions = { | 
|  | 10 | +		attrkey: '$', | 
|  | 11 | +		charkey: '_' | 
|  | 12 | +	}; | 
|  | 13 | + | 
| 7 | 14 | 	jQuery.extend({ | 
| 8 | 15 | 
 | 
| 9 | 16 | 		/**w | 
| 10 | 17 | 		 * Converts an xml response object from a $.ajax() call to a JSON object. | 
| 11 | 18 | 		 * | 
| 12 | 19 | 		 * @param xml | 
| 13 | 20 | 		 */ | 
| 14 |  | -		xml2json: function xml2json(xml) { | 
|  | 21 | +		xml2json: function xml2json(xml, options) { | 
|  | 22 | +			options = options || defaultOptions; | 
|  | 23 | + | 
| 15 | 24 | 			var result = {}; | 
| 16 | 25 | 
 | 
| 17 | 26 | 			for (var i in xml.childNodes) { | 
| 18 | 27 | 				var node = xml.childNodes[i]; | 
| 19 | 28 | 				if (node.nodeType === 1) { | 
| 20 |  | -					var child = node.hasChildNodes() ? xml2json(node) : node.nodevalue; | 
|  | 29 | +					var child = node.hasChildNodes() ? xml2json(node, options) : node.nodevalue; | 
| 21 | 30 | 					child = child === null ? {} : child; | 
| 22 | 31 | 
 | 
| 23 | 32 | 					if (result.hasOwnProperty(node.nodeName)) { | 
|  | 
| 34 | 43 | 
 | 
| 35 | 44 | 					// Add attributes if any | 
| 36 | 45 | 					if (node.attributes.length > 0) { | 
| 37 |  | -						result[node.nodeName]['@attributes'] = {}; | 
| 38 |  | -						child['@attributes'] = {}; | 
|  | 46 | +						result[node.nodeName][options.attrkey] = {}; | 
|  | 47 | +						child[options.attrkey] = {}; | 
| 39 | 48 | 						for (var j in node.attributes) { | 
| 40 | 49 | 							var attribute = node.attributes.item(j); | 
| 41 |  | -							child['@attributes'][attribute.nodeName] = attribute.value; | 
|  | 50 | +							child[options.attrkey][attribute.nodeName] = attribute.value; | 
| 42 | 51 | 						} | 
| 43 | 52 | 					} | 
| 44 | 53 | 
 | 
| 45 | 54 | 					// Add element value | 
| 46 | 55 | 					if (node.childElementCount === 0 && node.textContent !== null && node.textContent !== "") { | 
| 47 |  | -						child.value = node.textContent.trim(); | 
|  | 56 | +						child[options.charkey] = node.textContent.trim(); | 
| 48 | 57 | 					} | 
| 49 | 58 | 				} | 
| 50 | 59 | 			} | 
|  | 
0 commit comments