fast-xml-parser 3.20.3 → 3.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,6 +23,8 @@ To cover expenses, we're planning to launch [FXP Enterprise](https://github.com/
23
23
  </a>
24
24
  <a href="https://paypal.me/naturalintelligence"> <img src="static/img/support_paypal.svg" alt="Stubmatic donate button" width="200"/></a>
25
25
 
26
+ Check [ThankYouBackers](https://github.com/NaturalIntelligence/ThankYouBackers) for our contributors
27
+
26
28
  ## Users
27
29
  List of some applications/projects using Fast XML Parser. (Raise an issue to submit yours)
28
30
 
@@ -103,13 +105,19 @@ The list of users is collected either from the list published by Github, cummuni
103
105
 
104
106
  ## How to use
105
107
 
106
- To use it in **NPM package** install it first
108
+ ### Installation
109
+
110
+ To use it as an **NPM package**:
111
+
112
+ `npm install fast-xml-parser`
107
113
 
108
- `$npm install fast-xml-parser` or using [yarn](https://yarnpkg.com/) `$yarn add fast-xml-parser`
114
+ Or using [yarn](https://yarnpkg.com/):
115
+
116
+ `yarn add fast-xml-parser`
109
117
 
110
118
  To use it from a **CLI** install it globally with the `-g` option.
111
119
 
112
- `$npm install fast-xml-parser -g`
120
+ `npm install fast-xml-parser -g`
113
121
 
114
122
  To use it on a **webpage** include it from a [CDN](https://cdnjs.com/libraries/fast-xml-parser)
115
123
 
@@ -117,14 +125,14 @@ To use it on a **webpage** include it from a [CDN](https://cdnjs.com/libraries/f
117
125
 
118
126
 
119
127
  ```js
120
- var jsonObj = parser.parse(xmlData [,options] );
128
+ const jsonObj = parser.parse(xmlData [,options] );
121
129
  ```
122
130
 
123
131
  ```js
124
- var parser = require('fast-xml-parser');
125
- var he = require('he');
132
+ const parser = require('fast-xml-parser');
133
+ const he = require('he');
126
134
 
127
- var options = {
135
+ const options = {
128
136
  attributeNamePrefix : "@_",
129
137
  attrNodeName: "attr", //default is 'false'
130
138
  textNodeName : "#text",
@@ -141,27 +149,28 @@ var options = {
141
149
  hex: true,
142
150
  leadingZeros: true,
143
151
  //skipLike: /\+[0-9]{10}/
144
- }
152
+ },
145
153
  arrayMode: false, //"strict"
146
154
  attrValueProcessor: (val, attrName) => he.decode(val, {isAttributeValue: true}),//default is a=>a
147
155
  tagValueProcessor : (val, tagName) => he.decode(val), //default is a=>a
148
- stopNodes: ["parse-me-as-string"]
156
+ stopNodes: ["parse-me-as-string"],
157
+ alwaysCreateTextNode: false
149
158
  };
150
159
 
151
160
  if( parser.validate(xmlData) === true) { //optional (it'll return an object in case it's not valid)
152
- var jsonObj = parser.parse(xmlData,options);
161
+ let jsonObj = parser.parse(xmlData,options);
153
162
  }
154
163
 
155
164
  // Intermediate obj
156
- var tObj = parser.getTraversalObj(xmlData,options);
157
- var jsonObj = parser.convertToJson(tObj,options);
165
+ const tObj = parser.getTraversalObj(xmlData,options);
166
+ let jsonObj = parser.convertToJson(tObj,options);
158
167
 
159
168
  ```
160
169
  As you can notice in the above code, validator is not embedded with in the parser and expected to be called separately. However, you can pass `true` or validation options as 3rd parameter to the parser to trigger validator internally. It is same as above example.
161
170
 
162
171
  ```js
163
172
  try{
164
- var jsonObj = parser.parse(xmlData,options, true);
173
+ let jsonObj = parser.parse(xmlData,options, true);
165
174
  }catch(error){
166
175
  console.log(error.message)
167
176
  }
@@ -200,7 +209,7 @@ Validator returns the following object in case of error;
200
209
  * **tagValueProcessor** : Process tag value during transformation. Like HTML decoding, word capitalization, etc. Applicable in case of string only.
201
210
  * **attrValueProcessor** : Process attribute value during transformation. Like HTML decoding, word capitalization, etc. Applicable in case of string only.
202
211
  * **stopNodes** : an array of tag names which are not required to be parsed. Instead their values are parsed as string.
203
-
212
+ * **alwaysCreateTextNode** : When `true`, forces the parser always return a property for the `textNodeName` even if there are no attributes or node children.
204
213
  </details>
205
214
 
206
215
  <details>
@@ -223,18 +232,18 @@ $cat xmlfile.xml | xml2js [-ns|-a|-c|-v|-V] [-o outputfile.json]
223
232
  <summary>To use it <b>on webpage</b></summary>
224
233
 
225
234
  ```js
226
- var result = parser.validate(xmlData);
235
+ const result = parser.validate(xmlData);
227
236
  if (result !== true) console.log(result.err);
228
- var jsonObj = parser.parse(xmlData);
237
+ const jsonObj = parser.parse(xmlData);
229
238
  ```
230
239
  </details>
231
240
 
232
241
  ### JSON / JS Object to XML
233
242
 
234
243
  ```js
235
- var Parser = require("fast-xml-parser").j2xParser;
244
+ const Parser = require("fast-xml-parser").j2xParser;
236
245
  //default options need not to set
237
- var defaultOptions = {
246
+ const defaultOptions = {
238
247
  attributeNamePrefix : "@_",
239
248
  attrNodeName: "@", //default is false
240
249
  textNodeName : "#text",
@@ -245,10 +254,11 @@ var defaultOptions = {
245
254
  indentBy: " ",
246
255
  supressEmptyNode: false,
247
256
  tagValueProcessor: a=> he.encode(a, { useNamedReferences: true}),// default is a=>a
248
- attrValueProcessor: a=> he.encode(a, {isAttributeValue: isAttribute, useNamedReferences: true})// default is a=>a
257
+ attrValueProcessor: a=> he.encode(a, {isAttributeValue: isAttribute, useNamedReferences: true}),// default is a=>a
258
+ rootNodeName: "element"
249
259
  };
250
- var parser = new Parser(defaultOptions);
251
- var xml = parser.parse(json_or_js_obj);
260
+ const parser = new Parser(defaultOptions);
261
+ const xml = parser.parse(json_or_js_obj);
252
262
  ```
253
263
 
254
264
  <details>
@@ -267,6 +277,7 @@ With the correct options, you can get the almost original XML without losing any
267
277
  * **supressEmptyNode** : If set to `true`, tags with no value (text or nested tags) are written as self closing tags.
268
278
  * **tagValueProcessor** : Process tag value during transformation. Like HTML encoding, word capitalization, etc. Applicable in case of string only.
269
279
  * **attrValueProcessor** : Process attribute value during transformation. Like HTML encoding, word capitalization, etc. Applicable in case of string only.
280
+ * **rootNodeName** : When input js object is array, parser uses array index by default as tag name. You can set this property for proper response.
270
281
  </details>
271
282
 
272
283
  ## Benchmark
package/package.json CHANGED
@@ -1,19 +1,18 @@
1
1
  {
2
2
  "name": "fast-xml-parser",
3
- "version": "3.20.3",
3
+ "version": "3.21.0",
4
4
  "description": "Validate XML or Parse XML to JS/JSON very fast without C/C++ based libraries",
5
5
  "main": "./src/parser.js",
6
6
  "scripts": {
7
- "test": "jasmine spec/*spec.js",
7
+ "test": "npx nyc jasmine spec/*spec.js",
8
8
  "unit": "jasmine",
9
+ "coverage": "npx nyc report --reporter html --reporter text -t .nyc_output --report-dir .nyc_output/summary",
9
10
  "perf": "node ./benchmark/perfTest3.js",
10
11
  "lint": "eslint src/*.js spec/*.js",
11
12
  "bundle": "webpack && webpack --config webpack-prod.config.js",
12
- "coverage": "istanbul cover -x \"cli.js\" -x \"spec/*spec.js\" jasmine spec/*spec.js;",
13
- "coverage:check": "istanbul check-coverage --branch 90 --statement 90",
14
13
  "prettier": "prettier --write src/**/*.js",
15
14
  "publish-please": "publish-please",
16
- "prepublishOnly": "publish-please guard"
15
+ "checkReadiness": "publish-please --dry-run"
17
16
  },
18
17
  "bin": {
19
18
  "xml2js": "./cli.js"
@@ -76,8 +75,6 @@
76
75
  "babel-loader": "^8.2.2",
77
76
  "eslint": "^5.16.0",
78
77
  "he": "^1.2.0",
79
- "http-server": "^0.12.3",
80
- "istanbul": "^0.4.5",
81
78
  "jasmine": "^3.6.4",
82
79
  "nimnjs": "^1.3.2",
83
80
  "prettier": "^1.19.1",
@@ -91,6 +88,7 @@
91
88
  "url": "https://paypal.me/naturalintelligence"
92
89
  },
93
90
  "dependencies": {
91
+ "nyc": "^15.1.0",
94
92
  "strnum": "^1.0.4"
95
93
  }
96
94
  }
package/src/json2xml.js CHANGED
@@ -32,6 +32,7 @@ const props = [
32
32
  'supressEmptyNode',
33
33
  'tagValueProcessor',
34
34
  'attrValueProcessor',
35
+ 'rootNodeName', //when array as root
35
36
  ];
36
37
 
37
38
  function Parser(options) {
@@ -79,6 +80,11 @@ function Parser(options) {
79
80
  }
80
81
 
81
82
  Parser.prototype.parse = function(jObj) {
83
+ if(Array.isArray(jObj) && this.options.rootNodeName && this.options.rootNodeName.length > 1){
84
+ jObj = {
85
+ [this.options.rootNodeName] : jObj
86
+ }
87
+ }
82
88
  return this.j2x(jObj, 0).val;
83
89
  };
84
90
 
package/src/nimndata.js CHANGED
@@ -48,7 +48,7 @@ const _e = function(node, e_schema, options) {
48
48
  //attributes can't be repeated. hence check in children tags only
49
49
  str += chars.arrStart;
50
50
  const itemSchema = e_schema[0];
51
- //var itemSchemaType = itemSchema;
51
+ //const itemSchemaType = itemSchema;
52
52
  const arr_len = node.length;
53
53
 
54
54
  if (typeof itemSchema === 'string') {
package/src/node2json.js CHANGED
@@ -6,7 +6,7 @@ const convertToJson = function(node, options, parentTagName) {
6
6
  const jObj = {};
7
7
 
8
8
  // when no child node or attr is present
9
- if ((!node.child || util.isEmptyObject(node.child)) && (!node.attrsMap || util.isEmptyObject(node.attrsMap))) {
9
+ if (!options.alwaysCreateTextNode && (!node.child || util.isEmptyObject(node.child)) && (!node.attrsMap || util.isEmptyObject(node.attrsMap))) {
10
10
  return util.isExist(node.val) ? node.val : '';
11
11
  }
12
12
 
@@ -19,10 +19,10 @@ const _cToJsonStr = function(node, options, level) {
19
19
  const keys = Object.keys(node.child);
20
20
 
21
21
  for (let index = 0; index < keys.length; index++) {
22
- var tagname = keys[index];
22
+ const tagname = keys[index];
23
23
  if (node.child[tagname] && node.child[tagname].length > 1) {
24
24
  jObj += '"' + tagname + '" : [ ';
25
- for (var tag in node.child[tagname]) {
25
+ for (let tag in node.child[tagname]) {
26
26
  jObj += _cToJsonStr(node.child[tagname][tag], options) + ' , ';
27
27
  }
28
28
  jObj = jObj.substr(0, jObj.length - 1) + ' ] '; //remove extra comma in last
package/src/parser.d.ts CHANGED
@@ -16,6 +16,7 @@ type X2jOptions = {
16
16
  tagValueProcessor: (tagValue: string, tagName: string) => string;
17
17
  attrValueProcessor: (attrValue: string, attrName: string) => string;
18
18
  stopNodes: string[];
19
+ alwaysCreateTextNode: boolean;
19
20
  };
20
21
  type strnumOptions = {
21
22
  hex: boolean;
@@ -45,7 +46,7 @@ type J2xOptionsOptional = Partial<J2xOptions>;
45
46
  type ESchema = string | object | Array<string|object>;
46
47
 
47
48
  type ValidationError = {
48
- err: { code: string; msg: string, line: number };
49
+ err: { code: string; msg: string, line: number, col: number };
49
50
  };
50
51
 
51
52
  export function parse(xmlData: string, options?: X2jOptionsOptional, validationOptions?: validationOptionsOptional | boolean): any;
package/src/util.js CHANGED
@@ -10,6 +10,7 @@ const getAllMatches = function(string, regex) {
10
10
  let match = regex.exec(string);
11
11
  while (match) {
12
12
  const allmatches = [];
13
+ allmatches.startIndex = regex.lastIndex - match[0].length;
13
14
  const len = match.length;
14
15
  for (let index = 0; index < len; index++) {
15
16
  allmatches.push(match[index]);
@@ -67,7 +68,7 @@ exports.getValue = function(v) {
67
68
  // const fakeCallNoReturn = function() {};
68
69
 
69
70
  exports.buildOptions = function(options, defaultOptions, props) {
70
- var newOptions = {};
71
+ let newOptions = {};
71
72
  if (!options) {
72
73
  return defaultOptions; //if there are not options
73
74
  }
package/src/validator.js CHANGED
@@ -35,7 +35,7 @@ exports.validate = function (xmlData, options) {
35
35
  }else if (xmlData[i] === '<') {
36
36
  //starting of tag
37
37
  //read until you reach to '>' avoiding any '>' in attribute value
38
-
38
+ let tagStartPos = i;
39
39
  i++;
40
40
 
41
41
  if (xmlData[i] === '!') {
@@ -71,7 +71,7 @@ exports.validate = function (xmlData, options) {
71
71
  if (!validateTagName(tagName)) {
72
72
  let msg;
73
73
  if (tagName.trim().length === 0) {
74
- msg = "There is an unnecessary space between tag name and backward slash '</ ..'.";
74
+ msg = "Invalid space after '<'.";
75
75
  } else {
76
76
  msg = "Tag '"+tagName+"' is an invalid name.";
77
77
  }
@@ -87,6 +87,7 @@ exports.validate = function (xmlData, options) {
87
87
 
88
88
  if (attrStr[attrStr.length - 1] === '/') {
89
89
  //self closing tag
90
+ const attrStrStart = i - attrStr.length;
90
91
  attrStr = attrStr.substring(0, attrStr.length - 1);
91
92
  const isValid = validateAttributeString(attrStr, options);
92
93
  if (isValid === true) {
@@ -96,17 +97,20 @@ exports.validate = function (xmlData, options) {
96
97
  //the result from the nested function returns the position of the error within the attribute
97
98
  //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
98
99
  //this gives us the absolute index in the entire xml, which we can use to find the line at last
99
- return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
100
+ return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));
100
101
  }
101
102
  } else if (closingTag) {
102
103
  if (!result.tagClosed) {
103
104
  return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
104
105
  } else if (attrStr.trim().length > 0) {
105
- return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, i));
106
+ return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
106
107
  } else {
107
108
  const otg = tags.pop();
108
- if (tagName !== otg) {
109
- return getErrorObject('InvalidTag', "Closing tag '"+otg+"' is expected inplace of '"+tagName+"'.", getLineNumberForPosition(xmlData, i));
109
+ if (tagName !== otg.tagName) {
110
+ let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
111
+ return getErrorObject('InvalidTag',
112
+ "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.",
113
+ getLineNumberForPosition(xmlData, tagStartPos));
110
114
  }
111
115
 
112
116
  //when there are no more tags, we reached the root level.
@@ -127,7 +131,7 @@ exports.validate = function (xmlData, options) {
127
131
  if (reachedRoot === true) {
128
132
  return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));
129
133
  } else {
130
- tags.push(tagName);
134
+ tags.push({tagName, tagStartPos});
131
135
  }
132
136
  tagFound = true;
133
137
  }
@@ -168,8 +172,12 @@ exports.validate = function (xmlData, options) {
168
172
 
169
173
  if (!tagFound) {
170
174
  return getErrorObject('InvalidXml', 'Start tag expected.', 1);
171
- } else if (tags.length > 0) {
172
- return getErrorObject('InvalidXml', "Invalid '"+JSON.stringify(tags, null, 4).replace(/\r?\n/g, '')+"' found.", 1);
175
+ }else if (tags.length == 1) {
176
+ return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
177
+ }else if (tags.length > 0) {
178
+ return getErrorObject('InvalidXml', "Invalid '"+
179
+ JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+
180
+ "' found.", {line: 1, col: 1});
173
181
  }
174
182
 
175
183
  return true;
@@ -181,11 +189,11 @@ exports.validate = function (xmlData, options) {
181
189
  * @param {*} i
182
190
  */
183
191
  function readPI(xmlData, i) {
184
- var start = i;
192
+ const start = i;
185
193
  for (; i < xmlData.length; i++) {
186
194
  if (xmlData[i] == '?' || xmlData[i] == ' ') {
187
195
  //tagname
188
- var tagname = xmlData.substr(start, i - start);
196
+ const tagname = xmlData.substr(start, i - start);
189
197
  if (i > 5 && tagname === 'xml') {
190
198
  return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));
191
199
  } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {
@@ -251,8 +259,8 @@ function readCommentAndCDATA(xmlData, i) {
251
259
  return i;
252
260
  }
253
261
 
254
- var doubleQuote = '"';
255
- var singleQuote = "'";
262
+ const doubleQuote = '"';
263
+ const singleQuote = "'";
256
264
 
257
265
  /**
258
266
  * Keep reading xmlData until '<' is found outside the attribute value.
@@ -269,7 +277,6 @@ function readAttributeStr(xmlData, i) {
269
277
  startChar = xmlData[i];
270
278
  } else if (startChar !== xmlData[i]) {
271
279
  //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa
272
- continue;
273
280
  } else {
274
281
  startChar = '';
275
282
  }
@@ -310,23 +317,23 @@ function validateAttributeString(attrStr, options) {
310
317
  for (let i = 0; i < matches.length; i++) {
311
318
  if (matches[i][1].length === 0) {
312
319
  //nospace before attribute name: a="sd"b="saf"
313
- return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(attrStr, matches[i][0]))
320
+ return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i]))
314
321
  } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {
315
322
  //independent attribute: ab
316
- return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(attrStr, matches[i][0]));
323
+ return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i]));
317
324
  }
318
325
  /* else if(matches[i][6] === undefined){//attribute without value: ab=
319
326
  return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}};
320
327
  } */
321
328
  const attrName = matches[i][2];
322
329
  if (!validateAttrName(attrName)) {
323
- return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(attrStr, matches[i][0]));
330
+ return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i]));
324
331
  }
325
332
  if (!attrNames.hasOwnProperty(attrName)) {
326
333
  //check for duplicate attribute.
327
334
  attrNames[attrName] = 1;
328
335
  } else {
329
- return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(attrStr, matches[i][0]));
336
+ return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i]));
330
337
  }
331
338
  }
332
339
 
@@ -373,7 +380,8 @@ function getErrorObject(code, message, lineNumber) {
373
380
  err: {
374
381
  code: code,
375
382
  msg: message,
376
- line: lineNumber,
383
+ line: lineNumber.line || lineNumber,
384
+ col: lineNumber.col,
377
385
  },
378
386
  };
379
387
  }
@@ -390,11 +398,16 @@ function validateTagName(tagname) {
390
398
 
391
399
  //this function returns the line number for the character at the given index
392
400
  function getLineNumberForPosition(xmlData, index) {
393
- var lines = xmlData.substring(0, index).split(/\r?\n/);
394
- return lines.length;
401
+ const lines = xmlData.substring(0, index).split(/\r?\n/);
402
+ return {
403
+ line: lines.length,
404
+
405
+ // column number is last line's length + 1, because column numbering starts at 1:
406
+ col: lines[lines.length - 1].length + 1
407
+ };
395
408
  }
396
409
 
397
- //this function returns the position of the last character of match within attrStr
398
- function getPositionFromMatch(attrStr, match) {
399
- return attrStr.indexOf(match) + match.length;
410
+ //this function returns the position of the first character of match within attrStr
411
+ function getPositionFromMatch(match) {
412
+ return match.startIndex + match[1].length;
400
413
  }
@@ -44,7 +44,8 @@ const defaultOptions = {
44
44
  attrValueProcessor: function(a, attrName) {
45
45
  return a;
46
46
  },
47
- stopNodes: []
47
+ stopNodes: [],
48
+ alwaysCreateTextNode: false
48
49
  //decodeStrict: false,
49
50
  };
50
51
 
@@ -67,7 +68,8 @@ const props = [
67
68
  'attrValueProcessor',
68
69
  'parseTrueNumberOnly',
69
70
  'numParseOptions',
70
- 'stopNodes'
71
+ 'stopNodes',
72
+ 'alwaysCreateTextNode'
71
73
  ];
72
74
  exports.props = props;
73
75