Skip to content

Commit 576af61

Browse files
committed
options
1 parent d640043 commit 576af61

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

js/xml2json.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,29 @@
44
* @example var json = $.xml2json(response);
55
*/
66
(function() {
7+
8+
// default options based on https://github.com/Leonidas-from-XIV/node-xml2js
9+
var defaultOptions = {
10+
attrkey: '$',
11+
charkey: '_'
12+
};
13+
714
jQuery.extend({
815

916
/**w
1017
* Converts an xml response object from a $.ajax() call to a JSON object.
1118
*
1219
* @param xml
1320
*/
14-
xml2json: function xml2json(xml) {
21+
xml2json: function xml2json(xml, options) {
22+
options = options || defaultOptions;
23+
1524
var result = {};
1625

1726
for (var i in xml.childNodes) {
1827
var node = xml.childNodes[i];
1928
if (node.nodeType === 1) {
20-
var child = node.hasChildNodes() ? xml2json(node) : node.nodevalue;
29+
var child = node.hasChildNodes() ? xml2json(node, options) : node.nodevalue;
2130
child = child === null ? {} : child;
2231

2332
if (result.hasOwnProperty(node.nodeName)) {
@@ -34,17 +43,17 @@
3443

3544
// Add attributes if any
3645
if (node.attributes.length > 0) {
37-
result[node.nodeName]['@attributes'] = {};
38-
child['@attributes'] = {};
46+
result[node.nodeName][options.attrkey] = {};
47+
child[options.attrkey] = {};
3948
for (var j in node.attributes) {
4049
var attribute = node.attributes.item(j);
41-
child['@attributes'][attribute.nodeName] = attribute.value;
50+
child[options.attrkey][attribute.nodeName] = attribute.value;
4251
}
4352
}
4453

4554
// Add element value
4655
if (node.childElementCount === 0 && node.textContent !== null && node.textContent !== "") {
47-
child.value = node.textContent.trim();
56+
child[options.charkey] = node.textContent.trim();
4857
}
4958
}
5059
}

0 commit comments

Comments
 (0)