forked from segmentio/xml-parser
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
171 lines (133 loc) · 2.58 KB
/
index.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/**
* Module dependencies.
*/
var debug = require('debug')('xml-parser');
/**
* Expose `parse`.
*/
module.exports = parse;
/**
* Parse the given string of `xml`.
*
* @param {String} xml
* @return {Object}
* @api public
*/
function parse(xml) {
xml = String(xml).trim();
// strip comments
xml = xml.replace(/<!--[\s\S]*?-->/g, '');
return document();
/**
* XML document.
*/
function document() {
var doc = { declaration: declaration() }, moreDecl;
while (true) {
moreDecl = declaration();
if (!moreDecl) { break; }
doc.declaration += moreDecl;
}
doc.root = tag();
return doc;
}
/**
* Declaration.
*/
function declaration() {
var m = match(/^<\?xml\s*/);
if (!m) return;
// tag
var node = {
attributes: {}
};
// attributes
while (!(eos() || is('?>'))) {
var attr = attribute();
if (!attr) return node;
node.attributes[attr.name] = attr.value;
}
match(/\?>\s*<\?.*?\?>/);
return node;
}
/**
* Tag.
*/
function tag() {
debug('tag %j', xml);
var m = match(/^<([\w-:.]+)\s*/);
if (!m) return;
// name
var node = {
name: m[1],
attributes: {},
children: []
};
// attributes
while (!(eos() || is('>') || is('?>') || is('/>'))) {
var attr = attribute();
if (!attr) return node;
node.attributes[attr.name] = attr.value;
}
// self closing tag
if (match(/^\s*\/>\s*/)) {
return node;
}
match(/\??>\s*/);
// content
node.content = content();
// children
var child;
while (child = tag()) {
node.children.push(child);
}
// closing
match(/^<\/[\w-:.]+>\s*/);
return node;
}
/**
* Text content.
*/
function content() {
debug('content %j', xml);
var m = match(/^([^<]*)/);
if (m) return m[1];
return '';
}
/**
* Attribute.
*/
function attribute() {
debug('attribute %j', xml);
var m = match(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);
if (!m) return;
return { name: m[1], value: strip(m[2]) }
}
/**
* Strip quotes from `val`.
*/
function strip(val) {
return val.replace(/^['"]|['"]$/g, '');
}
/**
* Match `re` and advance the string.
*/
function match(re) {
var m = xml.match(re);
if (!m) return;
xml = xml.slice(m[0].length);
return m;
}
/**
* End-of-source.
*/
function eos() {
return 0 == xml.length;
}
/**
* Check for `prefix`.
*/
function is(prefix) {
return 0 == xml.indexOf(prefix);
}
}