Socket
Socket
Sign inDemoInstall

fast-xml-parser

Package Overview
Dependencies
1
Maintainers
1
Versions
133
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    fast-xml-parser

Validate XML or Parse XML to JS/JSON very fast without C/C++ based libraries


Version published
Maintainers
1
Install size
91.7 kB
Created

Package description

What is fast-xml-parser?

The fast-xml-parser npm package is a fast and powerful XML parser and validator that can convert XML to a JavaScript object, JSON, or a traversable JS object. It can also convert a JS object to XML. It is designed to be very fast and efficient, and it provides various options to control the XML parsing and validation process.

What are fast-xml-parser's main functionalities?

XML to JSON Conversion

Converts XML data to a JSON object. The 'parse' function takes an XML string and optional options object, and returns a JSON representation of the XML.

const { parse } = require('fast-xml-parser');
const xmlData = '<note><to>User</to><from>Library</from><heading>Reminder</heading><body>Don't forget to subscribe.</body></note>';
const options = {};
const jsonObj = parse(xmlData, options);

JSON to XML Conversion

Converts a JSON object to an XML string. The 'j2xParser' constructor takes an options object, and the 'parse' method converts the JSON object to an XML string.

const { j2xParser } = require('fast-xml-parser');
const parser = new j2xParser({});
const jsonObj = { note: { to: 'User', from: 'Library', heading: 'Reminder', body: 'Don't forget to subscribe.' } };
const xmlData = parser.parse(jsonObj);

XML Validation

Validates the XML string. The 'validate' function checks if the given XML string is well-formed and returns a validation result.

const { validate } = require('fast-xml-parser');
const xmlData = '<note><to>User</to><from>Library</from></note>';
const validationResult = validate(xmlData);

Traversable Object Creation

Creates a traversable JavaScript object from XML. The 'XMLParser' constructor creates a parser instance, and the 'parse' method converts the XML string into a traversable JS object.

const { XMLParser } = require('fast-xml-parser');
const xmlData = '<note><to>User</to><from>Library</from></note>';
const parser = new XMLParser();
const traversableObject = parser.parse(xmlData);

Other packages similar to fast-xml-parser

Readme

Source

fast-xml-parser

Backers on Open Collective Sponsors on Open Collective Known Vulnerabilities NPM quality Travis ci Build Status Coverage Status Try me NPM total downloads

Validate XML, Parse XML to JS/JSON and vice versa, or parse XML to Nimn rapidly without C/C++ based libraries and no callback

To cover expenses, we're planning to launch FXP Enterprise edition in parallel. Watch it for further updates, if you're interested.

Donate $5

Stubmatic donate button

Check ThankYouBackers for our contributors

Users

List of some applications/projects using Fast XML Parser. (Raise an issue to submit yours)

The list of users is collected either from the list published by Github, cummunicated directly through mails/chat , or from other resources. If you feel that your name in the above list is incorrectly published or you're not the user of this library anymore then you can inform us to remove it. We'll do the necessary changes ASAP.

Main Features

FXP logo
  • Validate XML data syntactically
  • Transform XML to JSON or Nimn
  • Transform JSON back to XML
  • Works with node packages, in browser, and in CLI (press try me button above for demo)
  • Faster than any pure JS implementation.
  • It can handle big files (tested up to 100mb).
  • Various options are available to customize the transformation
    • You can parse CDATA as a separate property.
    • You can prefix attributes or group them to a separate property. Or they can be ignored from the result completely.
    • You can parse tag's or attribute's value to primitive type: string, integer, float, hexadecimal, or boolean. And can optionally decode for HTML char.
    • You can remove namespace from tag or attribute name while parsing
    • It supports boolean attributes, if configured.

How to use

Installation

To use it as an NPM package:

npm install fast-xml-parser

Or using yarn:

yarn add fast-xml-parser

To use it from a CLI install it globally with the -g option.

npm install fast-xml-parser -g

To use it on a webpage include it from a CDN

XML to JSON

const jsonObj = parser.parse(xmlData [,options] );
const parser = require('fast-xml-parser');
const he = require('he');

const options = {
    attributeNamePrefix : "@_",
    attrNodeName: "attr", //default is 'false'
    textNodeName : "#text",
    ignoreAttributes : true,
    ignoreNameSpace : false,
    allowBooleanAttributes : false,
    parseNodeValue : true,
    parseAttributeValue : false,
    trimValues: true,
    cdataTagName: "__cdata", //default is 'false'
    cdataPositionChar: "\\c",
    parseTrueNumberOnly: false,
    numParseOptions:{
      hex: true,
      leadingZeros: true,
      //skipLike: /\+[0-9]{10}/
    },
    arrayMode: false, //"strict"
    attrValueProcessor: (val, attrName) => he.decode(val, {isAttributeValue: true}),//default is a=>a
    tagValueProcessor : (val, tagName) => he.decode(val), //default is a=>a
    stopNodes: ["parse-me-as-string"],
    alwaysCreateTextNode: false
};

if( parser.validate(xmlData) === true) { //optional (it'll return an object in case it's not valid)
    let jsonObj = parser.parse(xmlData,options);
}

// Intermediate obj
const tObj = parser.getTraversalObj(xmlData,options);
let jsonObj = parser.convertToJson(tObj,options);

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.

try{
  let jsonObj = parser.parse(xmlData,options, true);
}catch(error){
  console.log(error.message)
}

Validator returns the following object in case of error;

{
  err: {
    code: code,
    msg: message,
    line: lineNumber,
  },
};
Note: he library is used in this example
OPTIONS :
  • attributeNamePrefix : prepend given string to attribute name for identification
  • attrNodeName: (Valid name) Group all the attributes as properties of given name.
  • ignoreAttributes : Ignore attributes to be parsed.
  • ignoreNameSpace : Remove namespace string from tag and attribute names.
  • allowBooleanAttributes : a tag can have attributes without any value
  • parseNodeValue : Parse the value of text node to float, integer, or boolean.
  • parseAttributeValue : Parse the value of an attribute to float, integer, or boolean.
  • trimValues : trim string values of an attribute or node
  • decodeHTMLchar : This options has been removed from 3.3.4. Instead, use tagValueProcessor, and attrValueProcessor. See above example.
  • cdataTagName : If specified, parser parse CDATA as nested tag instead of adding it's value to parent tag.
  • cdataPositionChar : It'll help to covert JSON back to XML without losing CDATA position.
  • parseTrueNumberOnly: if true then values like "+123", or "0123" will not be parsed as number.
  • arrayMode : When false, a tag with single occurrence is parsed as an object but as an array in case of multiple occurences. When true, a tag will be parsed as an array always excluding leaf nodes. When strict, all the tags will be parsed as array only. When instance of RegEx, only tags will be parsed as array that match the regex. When function a tag name is passed to the callback that can be checked.
  • tagValueProcessor : Process tag value during transformation. Like HTML decoding, word capitalization, etc. Applicable in case of string only.
  • attrValueProcessor : Process attribute value during transformation. Like HTML decoding, word capitalization, etc. Applicable in case of string only.
  • stopNodes : an array of tag names which are not required to be parsed. Instead their values are parsed as string.
  • alwaysCreateTextNode : When true, forces the parser always return a property for the textNodeName even if there are no attributes or node children.
To use from command line
$xml2js [-ns|-a|-c|-v|-V] <filename> [-o outputfile.json]
$cat xmlfile.xml | xml2js [-ns|-a|-c|-v|-V] [-o outputfile.json]
  • -ns : To include namespaces (by default ignored)
  • -a : To ignore attributes
  • -c : To ignore value conversion (i.e. "-3" will not be converted to number -3)
  • -v : validate before parsing
  • -V : only validate
To use it on webpage
const result = parser.validate(xmlData);
if (result !== true) console.log(result.err);
const jsonObj = parser.parse(xmlData);

JSON / JS Object to XML

const Parser = require("fast-xml-parser").j2xParser;
//default options need not to set
const defaultOptions = {
    attributeNamePrefix : "@_",
    attrNodeName: "@", //default is false
    textNodeName : "#text",
    ignoreAttributes : true,
    cdataTagName: "__cdata", //default is false
    cdataPositionChar: "\\c",
    format: false,
    indentBy: "  ",
    supressEmptyNode: false,
    tagValueProcessor: a=> he.encode(a, { useNamedReferences: true}),// default is a=>a
    attrValueProcessor: a=> he.encode(a, {isAttributeValue: isAttribute, useNamedReferences: true}),// default is a=>a
    rootNodeName: "element"
};
const parser = new Parser(defaultOptions);
const xml = parser.parse(json_or_js_obj);
OPTIONS :

With the correct options, you can get the almost original XML without losing any information.

  • attributeNamePrefix : Identify attributes with this prefix otherwise treat them as a tag.
  • attrNodeName: Identify attributes when they are grouped under single property.
  • ignoreAttributes : Don't check for attributes. Treats everything as tag.
  • encodeHTMLchar : This option has been removed from 3.3.4. Use tagValueProcessor, and attrValueProcessor instead. See above example.
  • cdataTagName : If specified, parse matching tag as CDATA
  • cdataPositionChar : Identify the position where CDATA tag should be placed. If it is blank then CDATA will be added in the last of tag's value.
  • format : If set to true, then format the XML output.
  • indentBy : indent by this char when format is set to true
  • supressEmptyNode : If set to true, tags with no value (text or nested tags) are written as self closing tags.
  • tagValueProcessor : Process tag value during transformation. Like HTML encoding, word capitalization, etc. Applicable in case of string only.
  • attrValueProcessor : Process attribute value during transformation. Like HTML encoding, word capitalization, etc. Applicable in case of string only.
  • rootNodeName : When input js object is array, parser uses array index by default as tag name. You can set this property for proper response.

Benchmark

XML to JSON

npm_xml2json_compare

report
file sizefxp 3.0 validator (rps)fxp 3.0 parser (rps)xml2js 0.4.19 (rps)
1.5k16581.0675814032.093234615.930805
1.5m14918.4779313.233660985.90682005
13m1.8344792351.135582008-1
1.3k with CDATA30583.3531943160.523428398.556349
1.3m with CDATA27.2926647152.688770097.966000795
1.6k with cdata,prolog,doctype27690.2608241433.985477872.399268
98m0.084738581480.2600104004-1
  • -1 indicates error or incorrect output.
JSON to XML

npm_xml2json_compare

report
file sizefxp 3.2 js to xmlxml2js 0.4.19 builder
1.3k160148.980110384.99401
1.1m173.63748318.611884025

Worth to mention

  • BigBit standard) : A standard to represent any number in the universe in comparatively less space and without precision loss. A standard to save memory to represent any text string in comparision of UTF encodings.
  • imglab : Speedup and simplify image labeling / annotation. Supports multiple formats, one click annotation, easy interface and much more. There are more than half million images are being annotated every month using this tool.
  • stubmatic : Create fake webservices, DynamoDB or S3 servers, Manage fake/mock stub data, Or fake any HTTP(s) call.
  • अनुमार्गक (anumargak) : The fastest and simple router for node js web frameworks with many unique features.
  • मुनीम (Muneem) : A webframework made for all team members. Fast and Featured.
  • शब्दावली (shabdawali) : Amazing human like typing effects beyond your imagination.

Contributors

This project exists thanks to all the people who contribute. [Contribute].

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

  • MIT License

Keywords

FAQs

Last updated on 31 Oct 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc