-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxml-processor.js
235 lines (211 loc) · 6.92 KB
/
xml-processor.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/*
the beast is intendedd to process large files containing a lot of smaller elements.
Every such element is processed and extracted and passed as DOM document containing only the element to callback
After the callback is finished, document is discarded.
Once element is matched, no matching inside the element is done.
You can use xpath on the document
matchedElements:
{
prefix: ''
nsUri: ''
name: ''
hasAttr : ''
}
*/
const libxmljs = require('libxmljs')
const fs = require('fs')
function processFile(matchedElements, file, cbProgress, cbElement, cbFinish) {
let parser = new libxmljs.SaxPushParser();
let progress={
file: file,
bytesTotal: fs.statSync(file).size,
bytesSoFar: 0,
done: false,
}
let stream = fs.createReadStream(file, { encoding: 'utf-8' });
stream
.on('data', (chunk) => {
parser.push(chunk);
progress.bytesSoFar+=chunk.length;
process.nextTick(()=>{cbProgress(progress)})
})
.on('end', ()=>{
//parser.push("\u0000");
stream.close();
cbFinish();
progress.done=true;
process.nextTick(()=>{cbProgress(progress)})
})
parser
.on('startDocument', () => {
})
.on('startElementNS', startElementNs)
.on('characters', characters)
.on('endElementNS', endElementNs)
.on('endDocument', () => {
})
let doc = null;
let currentElement = null;
let indent = "";
let nsDefs = {};
function startElementNs(elem, attrs, prefix, uri, namespace) {
//console.log(`${prefix}:${elem}`)
try {
//record namespace defs
namespace.forEach((ns)=>{
//console.log("storing namespace: "+ns[0]);
nsDefs[ns[0]]=ns[1];
});
if (currentElement != null) {
//inside matched element
let elm = new libxmljs.Element(doc, elem);
currentElement.addChild(elm)
namespace.forEach((ns)=>{
elm.defineNamespace(ns[0],ns[1])
})
elm.namespace(prefix, uri)
let a=[];
attrs.forEach((attr)=>{
if (attr[1]){
a[attr[1]+":"+attr[0]]=attr[3]
}
else {
a[attr[0]]=attr[3]
}
})
elm.attr(a);
currentElement = elm;
}
else if (isMatchedElement(matchedElements,elem, attrs, prefix, uri, namespace)) {
//element just matched
doc = new libxmljs.Document();
let elm = new libxmljs.Element(doc, elem);
doc.root(elm)
Object.keys(nsDefs).forEach((ns)=>{
if (nsDefs.hasOwnProperty(ns)){
//console.log(`defining namespace: ${ns}:${nsDefs[ns]}`);
elm.defineNamespace(ns,nsDefs[ns])
}
})
elm.namespace(prefix, uri)
let a=[];
attrs.forEach((attr)=>{
if (attr[1]){
a[attr[1]+":"+attr[0]]=attr[3]
}
else {
a[attr[0]]=attr[3]
}
})
elm.attr(a);
currentElement = elm
//console.log("Started root element:"+elem)
}
}
catch (error) {
console.log("!!!Error: ", error, error.stack)
}
}
function endElementNs(elem, prefix, uri) {
try {
if (currentElement != null) {
if (currentElement === doc.root()) {
cbElement(doc)
currentElement = null;
doc = null;
}
else {
//console.log(indent+"FINISHED child element:"+currentElement.name());
///indent=indent.substring(2)
currentElement = currentElement.parent()
}
}
}
catch (error) {
console.log("!!!Error: ", error, error.stack)
}
}
function characters(chars) {
if (currentElement != null) {
currentElement.addChild(new libxmljs.Text(doc, chars));
}
}
}
function isMatchedElement(matched, elem, attrs, prefix, uri, namespace){
let found=false;
matched.forEach((m)=>{
// if (elem=="KatastralniUzemi" && m.name=="KatastralniUzemi" && findAttrName(attrs,m.hasAttr)){
// console.log("KU")
// }
let prefixMatch = !m.prefix || (m.prefix && prefix && m.prefix==prefix);
let nameMatch = !m.name || m.name==elem;
let uriMatch = !m.uri || (m.uri && uri && m.uri==uri);
let hasAttrMatch = !m.hasAttr || (m.hasAttr && attrs && findAttrName(attrs,m.hasAttr));
found=found || prefixMatch && nameMatch && uriMatch && hasAttrMatch ;
})
return found;
}
function findAttrName(attrs, name){
let ret=false;
attrs.forEach((attrs)=>{
if ( attrs[0] == name ) ret=true;
})
return ret;
}
function getNamespaces(doc,nsDef) {
let namespaces = {};
doc.root().namespaces().map((ns) => {
namespaces[ns.prefix()] = ns.href();
});
if (nsDef){
Object.keys(nsDef).map((key)=>{
namespaces[key] = nsdef[key];
})
}
return namespaces;
}
function getValueAttr(doc, ns, xpath, obj, propName) {
if (doc.root().find(xpath, ns).length > 0) {
let val = doc.root().find(xpath, ns).map((elm) => {
return elm.value();
})
if (val.length==1) obj[propName]=val[0]
else obj[propName]=val;
}
}
let cbCodebookResolver=null;
function setCodebookResolver(cbResolveCodebook){
cbCodebookResolver=cbResolveCodebook;
}
function getValue(doc, ns, xpath, obj, propName){
return getValueFull(doc, ns, xpath, obj, propName, cbCodebookResolver)
}
function getValueFull(doc, ns, xpath, obj, propName, cbResolveCodebook) {
if (!obj.tags){
obj.tags=[];
}
if (doc.root().find(xpath, ns).length > 0) {
let val = doc.root().find(xpath, ns).map((elm) => {
let ret={
value: elm.text(),
tag: cbResolveCodebook?cbResolveCodebook(elm.namespace().prefix()+":"+elm.name(), elm.text()):null
}
return ret;
})
if (val.length==1) {
obj[propName]=val[0].value
if (val[0].tag) obj.tags.push(val[0].tag);
}
else {
obj[propName]=val.map((valElm)=>{return valElm.value});
val.forEach((valElm)=>{
if (valElm.tag) obj.tags.push(valElm.tag)
})
}
}
}
module.exports.processFile=processFile;
module.exports.getValue=getValue;
module.exports.getValueAttr = getValueAttr;
module.exports.getNamespaces = getNamespaces;
module.exports.setCodebookResolver = setCodebookResolver;