forked from dharmabruce/badgerfishjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
badgerfish.js
61 lines (50 loc) · 1.77 KB
/
badgerfish.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*global window $ DOMParser ActiveXObject*/
(function () {
"use strict";
function createXmlDoc(text) {
var parser, xmlDoc;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");
} else {
// Internet Explorer
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(text);
}
return xmlDoc;
}
function badgerFish(xml) {
var obj = {}, $el = $(xml);
if (typeof (xml) === "string") {
$el = $(createXmlDoc(xml));
}
// handle the simple case where an element
// has no attributes nor subelements
if (($el[0].attributes || []).length === 0 &&
$el.children().length === 0) {
return $el.text();
}
// handle attributes
$.each($el[0].attributes || [], function (value) {
obj["@" + value.name] = $el.attr(value.name);
});
// handle text if there are no subelements
if ($el.children().length === 0) {
obj.$ = $el.text();
}
// handle subelements
$el.children().each(function (element) {
if (obj[element.tagName] === undefined) {
obj[element.tagName] = badgerFish(element);
} else if ($.isArray(obj[element.tagName])) {
obj[element.tagName].push(badgerFish(element));
} else {
obj[element.tagName] = [obj[element.tagName]];
obj[element.tagName].push(badgerFish(element));
}
});
return obj;
}
window.badgerFish = badgerFish;
}());