-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickxml.js
61 lines (51 loc) · 1.75 KB
/
quickxml.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
module.exports = {
xmlToObj: (xml) => {
let root = {};
let name = null;
let obj = root;
const stack = [root];
xml.replace(/</g, '\n<')
.replace(/>/g, '>\n')
.replace(/\n\n/g ,'\n')
.split('\n')
.forEach((element) => {
const tag = element.match('<(/?)([^>]+)>');
if(tag) {
if(tag[1] === '/') {
obj = stack.pop();
} else {
name = tag[2];
let parent = obj;
obj = {};
if(parent[name] && !Array.isArray(parent[name])) {
parent[name] = [parent[name]];
}
if(Array.isArray(parent[name])) {
parent[name].push(obj);
} else {
parent[name] = obj;
}
stack.push(parent);
}
} else {
if(element.trim().length > 0) {
obj.value = element;
}
}
});
(function flatten(node) {
if(Array.isArray(node)) {
node.forEach((element) => flatten(element));
} else {
Object.keys(node).forEach((key) => {
if(Object.keys(node[key]).length === 1 && typeof node[key].value !== 'undefined') {
node[key] = node[key].value;
} else {
flatten(node[key]);
}
});
}
}(root));
return root;
}
}