-
Notifications
You must be signed in to change notification settings - Fork 3
/
parse.js
51 lines (40 loc) · 927 Bytes
/
parse.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
'use strict';
const parser = require('sax').parser;
function parse(data, config) {
const res = [];
const stack = [];
let pointer = res;
let trim = true;
let strict = true;
if (config && (config.strict !== undefined)) {
strict = config.strict;
}
if (config !== undefined) {
if (config.trim !== undefined) {
trim = config.trim;
}
}
const p = parser(strict);
p.ontext = function (e) {
if ((trim === false) || (e.trim() !== '')) {
pointer.push(e);
}
};
p.onopentag = function (e) {
const leaf = [e.name, e.attributes];
stack.push(pointer);
pointer.push(leaf);
pointer = leaf;
};
p.onclosetag = function () {
pointer = stack.pop();
};
p.oncdata = function (e) {
if ((trim === false) || (e.trim() !== '')) {
pointer.push('<![CDATA[' + e + ']]>');
}
};
p.write(data).close();
return res[0];
}
module.exports = parse;