-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
219 lines (158 loc) · 5.53 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
const fspath = require('path');
const libxmljs = require('libxmljs')
class Xlm2Object {
constructor(xml, mapping, options={}) {
if (options.html)
this.parser = libxmljs.parseHtml(xml, {preserveWhitespace: false})
else
this.parser = libxmljs.parseXml(xml, { preserveWhitespace: false, noerror: true });
this.mapping = mapping;
this.options = options;
}
/**
* Extract object from xml given a mapping
* @param {String} xml as string
* @param {Object} mapping mapping defined as specified in documentation
* @param {Object} options={}
*/
static extract(xml, mapping, options={}) {
const extractor = new Xlm2Object(xml, mapping, options);
return extractor.extract();
}
/**
* Extract xml arccording to given mapping
* @param {String} xml xml as string
* @param {Object} mapping mapping define according to documentation
*/
extract() {
const object = {};
for(const key in this.mapping) {
const extraction = this.extractKey(this.mapping[key])
if (extraction !== undefined)
object[key] = extraction;
}
return object;
}
/**
* Extract one single key given xpath and options
* @param {Object | String} options options given according to documentation (if string is given the options is converted to { path: options}
*
* @return {Array | Object | String} return object designed by the path (could be a string, an array or object)
*/
extractKey(options) {
if (typeof options === 'string')
options = {path: options}
if (options.tree && options.apply)
throw new Error('Apply cannot be used with tree')
const nothing = (anything) => anything || options.default;
const apply = options.apply || nothing;
let transform = (value) => {
if (!options.array || Array.isArray(value))
return apply(value);
if (!value)
return [];
return [apply(value)];
}
if (options.isHtml)
return transform(this._extractHtmlKey(options));
if (options.mapping)
return transform(this._extracItemsKey(options));
if (options.path)
return transform(this._extractPlainKey(options));
throw new Error('Path format not recognized');
}
/**
* Find node given an xpath
* @param {String} path xpath
*
* @returns {Array{Element}} array of elements
*/
extractNodes(path, tolerance=false) {
const nodes = this.parser.find(path, this.options.namespaces)
const isTolerant = this.options.tolerance || tolerance
if (!isTolerant && nodes.length === 0)
throw new Error(`No element for this path: ${path}`);
return nodes;
}
/**
* Extract simple key (attr or text)
* @param {String} path xpath
*
* @return {Array<String> | String} returrn array of extracted texts
*/
_extractPlainKey({path, array=false, tolerance=false}) {
const nodes = this.extractNodes(path, tolerance);
const value = this._extractValue(nodes, (node) => {
if (node.type() == 'attribute')
return node.value();
if (node.text)
return node.text();
if (node.type() == 'cdata')
return node._ref.content;
return node.toString();
})
return value;
}
/**
* Extract html content from key
* @param {String} path xpath
*
* @return {Array<String> | String} return array of html content or single html content in a string
*/
_extractHtmlKey({path, tolerance=false}) {
const nodes = this.extractNodes(path, tolerance);
return this._extractValue(nodes, (node) => {
const stripTagStart = new RegExp(`^<${node.name()}[^>]*>`);
const stripTagEnd = new RegExp(`</${node.name()}>$`);
let innerHtml = node.toString();
innerHtml = innerHtml.replace(stripTagStart, '')
innerHtml = innerHtml.replace(stripTagEnd, '')
return innerHtml;
});
}
/**
* Extract nested objects (reccursive)
* @param {String} {path xpath
* @param {Object} mapping} mapping for nested objects (relative)
*
* @return {Array | Object | String}
*/
_extracItemsKey({path, mapping, tolerance=false, tree}) {
const nodes = this.extractNodes(path, tolerance);
return this._extractValue(nodes, (node, index) => {
const object = {};
const entries = Object.entries(mapping);
const nthchild = isNaN(index) ? '' : `[${index+1}]`;
for(let i=0; i<entries.length; i++) {
const options = (typeof entries[i][1] === 'string') ? {path: entries[i][1]} : Object.assign({}, entries[i][1]);
const key = entries[i][0];
let globalPath = fspath.join(path + nthchild, options.path)
// Keep relative path
if (path.startsWith('//'))
globalPath = `/${globalPath}`
options.path = globalPath;
object[key] = this.extractKey(options);
}
if (tree) {
const reccursivePath = fspath.join(path + nthchild, tree)
const _childrens = this._extracItemsKey({path: reccursivePath, mapping, tolerance: true, tree})
if (_childrens)
object._childrens = Array.isArray(_childrens) ? _childrens : [_childrens];
}
return object;
})
}
/**
* Apply function to one or multiple nodes
* @param {Array[Element]} nodes
* @param {Function} func function to apply to the node to retrive the value
*/
_extractValue(nodes, func) {
if (nodes.length === 0)
return
if (nodes.length === 1)
return func(nodes[0])
return nodes.map((node, index) => func(node, index));
}
}
module.exports = Xlm2Object;