Security News
vlt Debuts New JavaScript Package Manager and Serverless Registry at NodeConf EU
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
fast-xml-parser
Advanced tools
Validate XML or Parse XML to JS/JSON very fast without C/C++ based libraries
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.
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);
xml2js is a similar npm package that provides XML to JavaScript object conversion. It includes options to customize the parsing process and supports builder options for converting back to XML. Compared to fast-xml-parser, xml2js may be slower but offers a more feature-rich API for handling complex XML structures.
xml-js is another npm package that converts XML text to a JavaScript object and vice versa. It can also convert XML to JSON and supports compact and non-compact modes. While fast-xml-parser focuses on speed, xml-js provides a more extensive set of conversion options.
libxmljs is a Node.js package that provides bindings to the libxml C library. It allows for parsing and serializing XML and includes XPath and XSLT support. It is different from fast-xml-parser in that it is a binding to a native library, which may offer performance benefits and additional XML processing features.
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.
Check ThankYouBackers for our contributors
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.
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
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,
},
};
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.true
, forces the parser always return a property for the textNodeName
even if there are no attributes or node children.$xml2js [-ns|-a|-c|-v|-V] <filename> [-o outputfile.json]
$cat xmlfile.xml | xml2js [-ns|-a|-c|-v|-V] [-o outputfile.json]
const result = parser.validate(xmlData);
if (result !== true) console.log(result.err);
const jsonObj = parser.parse(xmlData);
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);
With the correct options, you can get the almost original XML without losing any information.
when
format is set to true
true
, tags with no value (text or nested tags) are written as self closing tags.file size | fxp 3.0 validator (rps) | fxp 3.0 parser (rps) | xml2js 0.4.19 (rps) |
---|---|---|---|
1.5k | 16581.06758 | 14032.09323 | 4615.930805 |
1.5m | 14918.47793 | 13.23366098 | 5.90682005 |
13m | 1.834479235 | 1.135582008 | -1 |
1.3k with CDATA | 30583.35319 | 43160.52342 | 8398.556349 |
1.3m with CDATA | 27.29266471 | 52.68877009 | 7.966000795 |
1.6k with cdata,prolog,doctype | 27690.26082 | 41433.98547 | 7872.399268 |
98m | 0.08473858148 | 0.2600104004 | -1 |
file size | fxp 3.2 js to xml | xml2js 0.4.19 builder |
---|---|---|
1.3k | 160148.9801 | 10384.99401 |
1.1m | 173.6374831 | 8.611884025 |
This project exists thanks to all the people who contribute. [Contribute].
Thank you to all our backers! 🙏 [Become a backer]
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]
FAQs
Validate XML, Parse XML, Build XML without C/C++ based libraries
The npm package fast-xml-parser receives a total of 19,537,697 weekly downloads. As such, fast-xml-parser popularity was classified as popular.
We found that fast-xml-parser demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
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.
Security News
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
Security News
Research
The Socket Research Team uncovered a malicious Python package typosquatting the popular 'fabric' SSH library, silently exfiltrating AWS credentials from unsuspecting developers.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.