-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathXML.js
69 lines (63 loc) · 1.91 KB
/
XML.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
64
65
66
67
68
69
var libxmljs = require("libxmljs");
exports.stringify = stringify;
exports.parse = parse;
function stringify (obj) {
var xml = '';
for (var key in obj) {
var value = obj[key];
if (Array.isArray(value)) {
value.forEach(function (item) {
if (typeof item === 'object')
xml += '<' + key + '>' + stringify(item) + '</' + key + '>';
else
xml += '<' + key + '>' + item + '</' + key + '>';
});
} else if (typeof value === 'object') {
xml += '<' + key + '>' + stringify(value) + '</' + key + '>';
} else {
xml += '<' + key + '>' + value + '</' + key + '>';
}
}
return xml;
}
function parse (data) {
var element = data instanceof libxmljs.Document || data instanceof libxmljs.Element ? data : libxmljs.parseXml(data);
var obj = {};
if (element instanceof libxmljs.Document) {
element = element.root();
obj[element.name()] = parse(element);
} else {
var children = element.childNodes();
if (children.length) {
children.forEach(function (child) {
var name = child.name(), isTextNode = hasTextNode(child);
if (Array.isArray(obj[name])) {
obj[name].push(isTextNode ? child.text() : parse(child));
} else if (obj[name]) {
var oldValue = obj[name];
obj[name] = [oldValue, isTextNode ? child.text() : parse(child)];
} else if (isTextNode) {
obj[name] = child.text();
} else {
obj[name] = parse(child);
}
});
} else {
if (hasTextNode(element))
obj[element.name()] = element.text();
else
obj = parseAttributes(element);
}
}
return obj;
}
function parseAttributes (element) {
var obj = {};
element.attrs().forEach(function (attr) {
obj[attr.name()] = attr.value();
});
return obj;
}
function hasTextNode (child) {
return child.childNodes().length > 0 && child.childNodes()[0].name() === 'text';
}