-
Notifications
You must be signed in to change notification settings - Fork 0
/
tinyXML2JSON.js
63 lines (60 loc) · 1.75 KB
/
tinyXML2JSON.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
62
63
var tinyXML2JSON = (function(){
function convertX2J(xmlDoc) {
var attr,
child,
attrs = xmlDoc.attributes,
children = xmlDoc.childNodes,
key = xmlDoc.nodeType,
obj = {},
i = -1;
if (key === 1 && attrs.length) {
obj[key = '@attributes'] = {};
while (attr = attrs.item(++i)) {
obj[key][attr.nodeName] = attr.nodeValue;
}
i = -1;
} else if (key === 3) {
obj = xmlDoc.nodeValue;
} else if(key === 4) {
obj = xmlDoc.data || xmlDoc.nodeValue;
}
while (child = children.item(++i)) {
key = child.nodeName;
if (obj.hasOwnProperty(key)) {
if (obj.toString.call(obj[key]) !== '[object Array]') {
obj[key] = [obj[key]];
}
obj[key].push(convertX2J(child));
}
else {
obj[key] = convertX2J(child);
}
}
return obj;
}
function parseXML(xmlStr) {
var xmlDoc;
if (window.DOMParser) {
xmlDoc = (new DOMParser()).parseFromString(xmlStr,'text/xml');
} else if (window.ActiveXObject) {
xmlDoc = [new ActiveXObject('Microsoft.XMLDOM'), xmlStr];
xmlDoc[0].async = false;
xmlDoc[0].loadXML(xmlDoc[1]);
xmlDoc = xmlDoc[0];
}
return xmlDoc;
}
return {
convert: function(xmlStr) {
var xmlDoc;
if(typeof xmlStr === 'string') {
xmlDoc = parseXML(xmlStr);
return convertX2J(xmlDoc);
} else if(Object.prototype.toString.call(xmlStr) === '[object XMLDocument]' ||
Object.prototype.toString.call(xmlStr) === '[object Document]') {
// 经测试 chrome31 虽然全局有 XMLDocument 但是 Object.prototype.toString.call(xmlStr) 仍为 [object Document]
return convertX2J(xmlStr);
}
}
}
})();