-
Notifications
You must be signed in to change notification settings - Fork 0
/
xml.js
87 lines (78 loc) · 1.5 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// by zestylemonade
const isalpha = c => /[a-z]/i.test(c);
const isspace = c => /\s/.test(c);
class Node {
constructor(type, parent) {
this.type = type;
this.parent = parent;
this.children = [];
if(parent) parent.children.push(this);
}
}
function read(gen) {
let buf = "";
while(isalpha(gen.peek())) buf += gen.next();
return buf;
}
function string(gen) {
const raw = read(gen);
if(raw) return raw;
let buf = "";
gen.next();
while(!gen.done()) {
if(gen.peek() === '"') break;
if(gen.peek() === '\\') gen.next();
buf += gen.next();
}
gen.next();
return buf;
}
function generate(gen, parent) {
let buf = "";
while(!gen.done()) {
if(gen.peek() === '<') {
if(tag()) return;
} else {
buf += gen.next();
}
}
function tag() {
flush();
gen.next();
if(gen.peek() === '/') return true;
const node = new Node("element", parent);
node.name = read(gen);
node.attrs = new Map();
while(gen.next() !== '>') {
if(gen.peek() == '/') {
gen.next();
gen.next();
return false;
}
const key = read(gen);
gen.next();
const value = string(gen);
node.attrs.set(key, value);
}
generate(gen, node);
return false;
}
function flush() {
if(!buf) return;
const node = new Node("text", parent);
node.data = buf;
buf = "";
}
}
function parse(xml) {
let i = 0;
const root = new Node("root", null);
const gen = {
next: () => xml[i++],
peek: () => xml[i],
done: () => i >= xml.length,
};
generate(gen, root);
return root;
}
module.exports = parse;