-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
374 lines (326 loc) · 12.7 KB
/
main.ts
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import * as parseBoolean from "parse-string-boolean";
import {ToJSONOptions, ToObjectOptions} from "./out/main";
export type OnAttribute = {
attributes: object,
raw: string
} | false
export type TrimXML = {
XML: string,
Declaration: string
}
/** XML Utils **/
class XMLUtils {
public ignoreElements(arr:string[], start: number, end: number) {
return arr.splice(start,end)
}
public ignoreElement(element: string): boolean {
if (element.includes('?xml') || element.includes('/')) {
return true
}
else {
return false
}
}
public convertTypesAuto(data: any): any {
//console.log(data)
if ((new Date(data)).getTime() > 0) {
return data;
}
else if (!isNaN(parseFloat(data))) {
return parseFloat(data);
}
else if (parseBoolean(data) !== null) {
return parseBoolean(data);
}
else {
return data;
}
}
public elementFromString(str: string): string {
if (str !== undefined) {
let parsedStr = str.replace(">", " ").replace("/", " ").split(" ")
if (parsedStr[0] !== "") {
return parsedStr[0]
} else {
return parsedStr[1]
}
}
}
public valueFromElement(str: string): object {
if (str !== undefined) {
let parsedStr = str.replace(">", " ").replace("/", " ").split(" ")
parsedStr.shift()
if (parsedStr[0] !== "") {
// @ts-ignore
if (this.onAttribute(str) !== false && this.onAttribute(str) !== undefined) {
// @ts-ignore
let {attributes,raw} = this.onAttribute(str)
let send = attributes
send["value"] = this.convertTypesAuto(parsedStr.join(" ").replace(raw, "").trim())
return send
}
else {
return this.convertTypesAuto(parsedStr.join(" "))
}
}
}
}
public findDuplicates(arr) {
let sorted_arr = arr.slice().sort(); // You can define the comparing function here.
// JS by default uses a crappy string compare.
// (we use slice to clone the array so the
// original array won't be modified)
let results = [];
for (let i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
return results;
}
public onAttribute(element): OnAttribute {
let send = {}
let rawAttributes = ""
element.split(" ").forEach((val) => {
if (val.includes("=")) {
const index = val.split("=")[0]
const value = val.split("=")[1].split(`"`)[1] || val.split("=")[1].split(`'`)[1] || val.split("=")[1].split("`")[1]
send[index] = value
if (val.includes("'")) {
rawAttributes = rawAttributes + `${index}='${value}'`
}
else if (val.includes(`"`)) {
rawAttributes = rawAttributes + `${index}="${value}"`
}
else if (val.includes("`")) {
rawAttributes = rawAttributes + index + "=`"+value+"`"
}
}
})
if (send) {
if (Object.keys(send).length !== 0) {
return {attributes: send, raw: rawAttributes};
}
}
else {
return false
}
}
public onDeclaration(rawStr: string) {
let str = rawStr.replace("<?","").replace("?>","")
if (this.onAttribute(str) !== false && this.onAttribute(str) !== undefined) {
// @ts-ignore
return this.onAttribute(str)
}
else {
return rawStr
}
}
public format() {
}
public nestedChild(arr: string[], ignoreParent?: boolean) {
let send = {}
let parent ="";
if (arr.indexOf(`/${this.elementFromString(arr[0])}>`) === arr.length-1) {
parent = this.elementFromString(arr[0]);
send[parent] = {}
}
else if (!ignoreParent) {
parent = this.elementFromString(arr[0])
send[parent] = {}
}
if (arr[0] === "extra>") {
}
arr.splice(0,1)
arr.splice(arr.length,1)
arr.forEach((value, index) => {
if (!this.ignoreElement(value)) {
let end = arr.indexOf(`/${this.elementFromString(value)}>`)
if (parent !== "") {
if ((end - index) === 1) {
let childElement = this.elementFromString(value)
send[parent][childElement] = this.valueFromElement(value)
}
else {
if (!value.includes("/")) {
let spliced = arr.splice(index,arr.indexOf("/"+value)-index)
let val = this.nestedChild(spliced)
if (send[parent] !== undefined) {
send[parent][Object.keys(val)[0]] = {}
send[parent][Object.keys(val)[0]] = val[Object.keys(val)[0]]
}
else {
send[Object.keys(val)[0]] = {}
send[Object.keys(val)[0]] = val[Object.keys(val)[0]]
}
}
}
}
else {
if ((end - index) === 1) {
let childElement = this.elementFromString(value)
send[childElement] = this.valueFromElement(value)
//console.table(send)
}
else {
if (!value.includes("/")) {
//console.table(arr)
let spliced = arr.splice(index,arr.indexOf("/"+value)-index)
let val = this.nestedChild(spliced)
if (send[parent] !== undefined) {
send[parent][Object.keys(val)[0]] = {}
send[parent][Object.keys(val)[0]] = val[Object.keys(val)[0]]
}
else {
send[Object.keys(val)[0]] = {}
send[Object.keys(val)[0]] = val[Object.keys(val)[0]]
}
}
}
}
}
})
return send
}
public trimXML(data, removeDeclaration?: boolean): TrimXML {
/*Default Values*/
removeDeclaration = removeDeclaration || false
let newXML = ""
let declaration = ""
data.split('\n').forEach(((value, index) => {
newXML = newXML + value.trim().replace("\r","")
}))
if (removeDeclaration) {
let start = newXML.lastIndexOf("<?")
let end = newXML.lastIndexOf("?>") + 2
declaration = newXML.slice(start,end)
newXML = newXML.replace(declaration,"")
}
// @ts-ignore
return {XML: newXML, Declaration: declaration};
}
}
function parser(XMLString: string, isRoot: boolean) {
const utils = new XMLUtils();
let {XML, Declaration} = utils.trimXML(XMLString,true)
let arrXML = XML.split("<")
let obj = {}
arrXML.shift()
arrXML.forEach((value, index) => {
arrXML[index] = "<"+value;
})
if (XML.split("<")[1] === undefined) return
let rootEle = XML.split("<")[1].split(" ")[0].split(">")[0]
let val = arrXML.filter(value => value ===`</${rootEle}>`)
arrXML.forEach((value, index) => {
if (value.split(">")[0].split(" ")[0] === (`<${rootEle}`) || value ===`</${rootEle}>`) delete arrXML[index]
})
arrXML = arrXML.filter((a) => a);
if (isRoot) {
if (Declaration !== undefined) { // @ts-ignore
obj["Declaration"] = utils.onDeclaration(Declaration).attributes
}
obj[rootEle] = {}
obj[rootEle] = utils.onAttribute(XML.split("<")[1])
}
if (val.length !== 0) {
arrXML.forEach(value => {
let send = ""
if (value === undefined) return
//console.log(value)
let attri = utils.onAttribute(value)
let ele = value.split("<")[1].split(" ")[0].split(">")[0].replace("/","")
//console.log(XML.match(new RegExp(`(<${ele})(.*)(<\/${ele}>)`))[0])
if ( value.split(">")[0].split(" ")[0] === (`<${ele}`)) {
var start = arrXML.indexOf(value)
let end = arrXML.indexOf(`</${ele}>`)
if (end-start > 1) {
send = arrXML.join("").match(new RegExp(`(<${ele})(.*)(<\/${ele}>)`))[0]
if (isRoot) {
obj[rootEle][ele] = parser(send, false)
if (utils.onAttribute(value) !== undefined) { // @ts-ignore
obj[rootEle][ele]["attributes"] = utils.onAttribute(XML.split("<")[1]).attributes
}
arrXML.slice(start, end).forEach(reVal => {
delete arrXML[arrXML.lastIndexOf(reVal)]
})
}
else {
obj[ele] = parser(send, false)
if (utils.onAttribute(value) !== undefined) { // @ts-ignore
obj[rootEle][ele]["attributes"] = utils.onAttribute(XML.split("<")[1]).attributes
}
arrXML.slice(start, end).forEach(reVal => {
delete arrXML[arrXML.lastIndexOf(reVal)]
})
}
}
else {
if (isRoot) {
obj[rootEle][ele] = utils.convertTypesAuto(value.match(new RegExp(`(>)(.*)`))[0].replace(">", ""))
if (utils.onAttribute(value) !== undefined) { // @ts-ignore
obj[rootEle][ele]["attributes"] = utils.onAttribute(XML.split("<")[1]).attributes
}
arrXML.slice(start, end).forEach(reVal => {
delete arrXML[arrXML.indexOf(reVal)]
})
}
else {
obj[ele] = utils.convertTypesAuto(value.match(new RegExp(`(>)(.*)`))[0].replace(">", ""))
if (utils.onAttribute(value) !== undefined) { // @ts-ignore
obj[rootEle][ele]["attributes"] = utils.onAttribute(XML.split("<")[1]).attributes
}
arrXML.slice(start, end).forEach(reVal => {
delete arrXML[arrXML.indexOf(reVal)]
})
}
}
//console.log(value+end)
}
//console.log(parser(send))
})
}
return obj
}
/*
* Converts XML String to JS Object
* */
export function toObject(XML: string,options?: ToObjectOptions):Object | void {
if (options === undefined) options = {ignoreAttributes: false, ignoreDeclaration: false, ignoreRoot: false}
if (options.ignoreAttributes === undefined) {
options.ignoreAttributes = false
}
else if (options.ignoreDeclaration === undefined) {
options.ignoreDeclaration = false
}
else if (options.ignoreRoot === undefined) {
options.ignoreRoot = false
}
return parser(XML, true)
}
//console.log(JSONParser('{"Ashp116":{"_id":"116","favirote":{ "_p":"teest","color":"Red","sport":"Tennis, Basket Ball","gaming":"None","hobby":"Game Development"}}}'))
/*
* Converts XML String to JSON
* */
export function toJSON(XML: string,options?: ToJSONOptions):Object | void {
if (options === undefined) options = {beautify: false, ignoreAttributes: false, ignoreDeclaration: false, ignoreRoot: false}
if (options.beautify === undefined) {
options.beautify = false
}
else if (options.ignoreAttributes === undefined) {
options.ignoreAttributes = false
}
else if (options.ignoreDeclaration === undefined) {
options.ignoreDeclaration = false
}
else if (options.ignoreRoot === undefined) {
options.ignoreRoot = false
}
let Parsed = parser(XML, true)
if (options.beautify) {
return JSON.stringify(Parsed,null, "\t")
}
else {
return JSON.stringify(Parsed)
}
}