### Install dependencies Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/benchmark/README.md Install the project dependencies using npm. ```shell $ npm i ``` -------------------------------- ### Install Fast XML Parser Globally Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/README.md Install the library globally to use it as a system command. ```bash $ npm install fast-xml-parser -g ``` -------------------------------- ### Install Fast XML Parser Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/README.md Install the library as a project dependency using npm or yarn. ```bash $ npm install fast-xml-parser ``` ```bash $ yarn add fast-xml-parser ``` -------------------------------- ### File Not Found Error Example Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md Illustrates the error message when the specified XML file does not exist. ```bash $ fxparser nonexistent.xml Seems an invalid file or stream.Error: ENOENT: no such file or directory... ``` -------------------------------- ### JSON Output Example Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md Demonstrates the formatted JSON output when parsing XML. ```json { "root": { "item": 1, "name": "test", "flag": true } } ``` -------------------------------- ### Permission Denied Error Example Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md Displays the error output when the CLI lacks permissions to access an XML file. ```bash $ fxparser /root/file.xml Seems an invalid file or stream.Error: EACCES: permission denied... ``` -------------------------------- ### Install Dedicated CLI Package Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md Install the recommended dedicated CLI package globally using npm. This package is actively developed and recommended for production use. ```bash npm install -g fxp-cli ``` -------------------------------- ### XML Predefined Entities Example Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/Entities.md Demonstrates the parsing of predefined XML entities like <, >, and &. ```xml Price is < $5 & quantity > 10 ``` -------------------------------- ### Use Fast XML Parser CLI Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/README.md Example of using the fast-xml-parser as a command-line interface tool. ```bash $ fxparser some.xml ``` -------------------------------- ### Use Fast XML Parser on a Webpage Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/README.md Example of including and using the parser in an HTML page via a CDN. ```html : ``` -------------------------------- ### Deprecated Built-in CLI Installation Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md If fast-xml-parser is installed globally, you can use the built-in CLI. Note that this is deprecated and may be removed in the future. ```bash npm install -g fast-xml-parser ``` -------------------------------- ### Update Local Package Installation Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/docs/CHECK_LIST.md Ensure local package installations are correct after potential changes. ```bash npm install ``` -------------------------------- ### Use Fast XML Parser in Node.js Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/README.md Example of parsing and building XML content within a Node.js project. ```javascript const { XMLParser, XMLBuilder, XMLValidator} = require("fast-xml-parser"); const parser = new XMLParser(); let jObj = parser.parse(XMLdata); const builder = new XMLBuilder(); const xmlContent = builder.build(jObj); ``` -------------------------------- ### Dedicated CLI Package Usage Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md After installing the dedicated CLI package, use the `fxp` command with options and an optional XML file. If no file is provided, it reads from standard input. ```bash # Now use: fxp [options] [file] ``` -------------------------------- ### Complex CLI Parsing Example Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md Combines multiple options to read, validate, preserve namespaces, keep values as strings, and write XML to a JSON file. ```bash # Read XML, validate, preserve namespaces, keep values as strings, write to file fxparser -v -ns -c data.xml -o output.json ``` -------------------------------- ### XML Parsing Error Example Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md Shows the error output when attempting to parse malformed XML. ```bash $ fxparser malformed.xml Error: Tag 'root' is not closed. ``` -------------------------------- ### Getting Current Path as String Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Illustrates using `toString` to get the current XML path as a string, with options to customize the separator and include namespaces. ```javascript // Path: ... tagValueProcessor: (tag, val, matcher) => { const path = matcher.toString(); // "root.users.user" const withNs = matcher.toString('.', true); // "root.users.soap:user" const custom = matcher.toString('/'); // "root/users/user" return val; } ``` -------------------------------- ### toString(separator?, includeNamespace?): string Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Gets the current path as a string, with an optional custom separator and the ability to include namespaces. ```APIDOC ## toString(separator?, includeNamespace?): string Gets the current path as a string. ```js // Path: ... tagValueProcessor: (tag, val, matcher) => { const path = matcher.toString(); // "root.users.user" const withNs = matcher.toString('.', true); // "root.users.soap:user" const custom = matcher.toString('/'); // "root/users/user" return val; } ``` ``` -------------------------------- ### Instantiate Expression with Options Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/types.md Examples of creating Expression instances with different patterns and custom separators. The separator option allows for non-default path delimiters. ```typescript const expr = new Expression("root.users.user[role=admin]:first"); const expr2 = new Expression("..item[id]:last", { separator: "/" }); ``` -------------------------------- ### Handle XML Namespaces with CLI Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md Use the CLI to preserve XML namespaces for processing. This example pipes the output to jq to select the 'soap:Envelope' element. ```bash fxparser -ns data.xml | jq '.["soap:Envelope"]' ``` -------------------------------- ### XXE Prevention Example Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/Entities.md Demonstrates how the parser prevents XXE attacks by default. External entities are blocked by the is-unsafe library, ensuring that external files are not loaded. ```javascript const maliciousXml = "\n \n ]>\n &xxe;\n"; const parser = new XMLParser(); const result = parser.parse(maliciousXml); // External entities are blocked by is-unsafe library ``` -------------------------------- ### Pull and Rebase Changes Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/docs/CHECK_LIST.md Before starting release tasks, ensure your local branch is up-to-date with the remote master by pulling and rebasing. ```bash git pull --rebase origin master ``` -------------------------------- ### Configure Entity Expansion Limits Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/errors.md Sets configuration options to limit entity expansions, preventing billion laughs and XXE attacks. This example defines maximum total expansions, expanded length, entity size, and the number of allowed entities. ```javascript const options = { processEntities: { maxTotalExpansions: 100, maxExpandedLength: 50000, maxEntitySize: 1000, maxEntityCount: 10 } }; ``` -------------------------------- ### Build XML String from JavaScript Object Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/README.md Shows how to construct an XML string from a JavaScript object using XMLBuilder. This example configures attribute prefixing and formatting for readability. ```javascript import { XMLBuilder } from 'fast-xml-builder'; // New package const builder = new XMLBuilder({ attributeNamePrefix: '@_', format: true }); const jsObject = { root: { item: { '@_id': '1', '#text': 'text' } } }; const xmlString = builder.build(jsObject); // // text // ``` -------------------------------- ### PathExpression Segment Breakdown Example Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Illustrates how a PathExpression string is parsed into an array of Segment objects. This shows the internal representation used by the parser. ```javascript [ { type: 'tag', tag: 'root' }, { type: 'tag', tag: 'users' }, { type: 'tag', tag: 'user', attrName: 'id', attrValue: '123', position: 'first', positionValue: 1 } ] ``` -------------------------------- ### Getting Current Path as Array Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Shows how to use `toArray` to retrieve the current XML path as an array of tag names. ```javascript tagValueProcessor: (tag, val, matcher) => { const pathArray = matcher.toArray(); // ["root", "users", "user"] return val; } ``` -------------------------------- ### Set Editor Value and Update Length Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/index.html Initializes the editor with sample XML content and then updates the displayed output length. This is part of the UI setup for demonstrating the parser. ```javascript editor.setValue(` +122233344550 Jack +122233344551 33 Yes Wed, 28 Mar 1979 12:13:14 +0300
New York Park Ave 1 1
Boston Centre St 33 24
+122233344553 Boris +122233344554 34 Yes Mon, 31 Aug 1970 02:03:04 +0300
Moscow Kahovka 1 2
Tula Lenina 3 78
`); updateLength(); ``` -------------------------------- ### Billion Laughs Prevention Example Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/Entities.md Illustrates how entity expansion is bounded to prevent Billion Laughs attacks. The parser will throw an error if entity expansion limits are exceeded. ```javascript const xml = "\n \n \n \n \n ]>\n &lol3;\n"; const parser = new XMLParser({ processEntities: { maxTotalExpansions: 100, maxExpandedLength: 50000 } }); try { const result = parser.parse(xml); } catch (error) { console.log('Entity expansion exceeded limits'); } ``` -------------------------------- ### XML Numeric Character References Example Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/Entities.md Shows how numeric character references (decimal and hexadecimal) are parsed into their corresponding Unicode characters. ```xml Unicode: © ® ``` -------------------------------- ### Implement a Custom Entity Decoder Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/Entities.md Provides a JavaScript class that implements a custom entity decoder. This example demonstrates how to manage a set of entities and replace them within a given text. It's useful for non-standard entity decoding, custom security policies, or integrating project-specific entity sets. ```javascript class CustomEntityDecoder { constructor() { this.entities = { ...defaultXmlEntities }; } setExternalEntities(entities) { Object.assign(this.entities, entities); } addInputEntities(entities) { Object.assign(this.entities, entities); } reset() { this.entities = { ...defaultXmlEntities }; } decode(text) { let result = text; for (const [entity, value] of Object.entries(this.entities)) { result = result.replace(new RegExp(`&${entity};`, 'g'), value); } return result; } setXmlVersion(version) { // Handle version-specific entity rules console.log(`XML version: ${version}`); } } const decoder = new CustomEntityDecoder(); const options = { entityDecoder: decoder }; ``` -------------------------------- ### CLI Options: Help and Version Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md Display help information or the version number using the respective CLI options. ```bash --help, -h ``` ```bash --version ``` -------------------------------- ### Ignore Attributes by Name Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/callbacks.md Use the ignoreAttributes callback function to skip specific attributes based on their names. This example ignores attributes starting with '_' or named 'internal'. ```javascript // Function form const options = { ignoreAttributes: (attrName, jPath) => { // Ignore internal attributes return attrName.startsWith('_') || attrName === 'internal'; } }; ``` -------------------------------- ### Run all benchmarks Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/benchmark/README.md Execute the full suite of benchmarks. ```shell $ npm t ``` -------------------------------- ### Filter Attributes Configuration Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/README.md Configure attribute filtering by providing a function that returns true for attributes to be ignored. This example ignores attributes starting with '_' or named 'internal'. ```javascript const options = { ignoreAttributes: (attrName) => { return attrName.startsWith('_') || attrName === 'internal'; } }; ``` -------------------------------- ### Callback Error Handling Example Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/errors.md Demonstrates how errors thrown in tagValueProcessor callbacks propagate up and can be caught by the main parse() call. Use try-catch around parse() to handle potential errors from callbacks. ```javascript const options = { tagValueProcessor: (tag, val) => { // If this throws, parse() will throw return JSON.parse(val); // Throws if val isn't valid JSON } }; try { const result = parser.parse(xmlData); } catch (error) { // Could be JSON parsing error from callback console.error('Processing error:', error.message); } ``` -------------------------------- ### Display fxp-cli Help Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md View the help information for the fxp-cli to understand its available commands and options. ```bash fxp --help ``` -------------------------------- ### Generate Browser Bundle Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/docs/CHECK_LIST.md Create the browser bundle for the project. ```bash npm run bundle ``` -------------------------------- ### Built-in CLI Usage Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md Use the `fxparser` command with options and an optional XML file. If no file is provided, it reads from standard input. ```bash fxparser [options] [file] ``` -------------------------------- ### Get Location Information for Validation Errors Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/errors.md Use XMLValidator.validate to get detailed error objects including line and column numbers. This snippet shows how to extract and display this location data for debugging. ```javascript try { const result = XMLValidator.validate(xmlData); if (result !== true) { const { line, col, msg } = result.err; // Highlight error location const lines = xmlData.split('\n'); console.error(`Line ${line}, Col ${col}:`); console.error(lines[line - 1]); console.error(' '.repeat(col - 1) + '^'); console.error(msg); } } catch (error) { console.error('Validation failed:', error); } ``` -------------------------------- ### List Documentation Files Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/INDEX.md Utilize the 'ls -la' command to list all files and directories within the documentation output folder. This provides an overview of the available documentation structure. ```bash # List all documents ls -la /workspace/home/output/ ``` -------------------------------- ### Instantiate XMLParser Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/XMLParser.md Create a new XMLParser instance. Basic instantiation uses default options. Custom options can be provided to modify parsing behavior. ```javascript // Basic parsing const parser = new XMLParser(); const result = parser.parse('text'); // With custom options const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_', parseTagValue: true, preserveOrder: false }); const result = parser.parse(xmlData); ``` -------------------------------- ### CLI Option: Output to File Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md Specify an output file for the parsed XML instead of writing to standard output. ```bash -o ``` -------------------------------- ### getCurrentTag(): string | undefined Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Gets the current tag name without its namespace. Useful for identifying the current element being processed. ```APIDOC ## getCurrentTag(): string | undefined Gets the current tag name without namespace. ```js tagValueProcessor: (tag, val, matcher) => { const current = matcher.getCurrentTag(); // e.g., "user" return val; } ``` ``` -------------------------------- ### Search Documentation Files Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/INDEX.md Employ the 'grep' command to perform a recursive search for specific keywords across all documentation files. This helps in locating relevant information within the documentation. ```bash # Search across documents grep -r "XMLParser" /workspace/home/output/ ``` -------------------------------- ### Retrieving Current Tag Name Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Shows how to get the current tag name using `getCurrentTag()` within a `tagValueProcessor` callback. ```javascript tagValueProcessor: (tag, val, matcher) => { const current = matcher.getCurrentTag(); // e.g., "user" return val; } ``` -------------------------------- ### Initialize XML Parser with Options Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/index.html Sets up default options for the XML parser, including CDATA handling, formatting, indentation, and attribute suppression. This function is typically called to configure the parser before use. ```javascript function defaultOptions() { return { // If true, CDATA will be parsed as text, not comments. cdataTagName: $("#parseCDATA").prop("checked") ? "#cdata" : false, format: true, indentBy: " ", suppressEmptyNode: false, preserveOrder: $("#preserveOrder").prop("checked") }; } ``` -------------------------------- ### getCurrentNamespace(): string | undefined Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Gets the namespace prefix of the current tag if it exists. This helps in distinguishing elements with the same name but different namespaces. ```APIDOC ## getCurrentNamespace(): string | undefined Gets the namespace prefix of the current tag if present. ```js // In XML: ... const ns = matcher.getCurrentNamespace(); // "soap" const tag = matcher.getCurrentTag(); // "Body" ``` ``` -------------------------------- ### Parse XML with UTF-8 BOM Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md The parser automatically handles UTF-8 BOM. This example shows parsing a file named utf8-with-bom.xml. ```bash fxparser utf8-with-bom.xml # Works fine ``` -------------------------------- ### Run builder benchmarks Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/benchmark/README.md Execute only the builder-specific benchmarks. ```shell $ npm run builder ``` -------------------------------- ### toArray(): string[] Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Gets the current path as an array of tag names, providing a structured representation of the element's location in the XML tree. ```APIDOC ## toArray(): string[] Gets the current path as an array of tag names. ```js tagValueProcessor: (tag, val, matcher) => { const pathArray = matcher.toArray(); // ["root", "users", "user"] return val; } ``` ``` -------------------------------- ### Getting Tag Occurrence Counter Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Demonstrates using `getCounter` to determine the occurrence count of the current tag at its level, distinct from its sibling position. ```javascript tagValueProcessor: (tag, val, matcher) => { const occurrence = matcher.getCounter(); if (tag === 'item' && occurrence === 1) { // First at this level } return val; } ``` -------------------------------- ### Read Documentation Files Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/INDEX.md Use the 'cat' command to read individual documentation files directly in the terminal. This is useful for quick access to specific files like README.md or API reference documents. ```bash # Read a document cat /workspace/home/output/README.md cat /workspace/home/output/api-reference/XMLParser.md ``` -------------------------------- ### Equivalent Code Options for Complex Parsing Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md Shows the JavaScript code equivalent to the complex CLI command, demonstrating how to configure the parser programmatically. ```javascript const parser = new XMLParser({ removeNSPrefix: false, // -ns parseTagValue: false, // -c ignoreAttributes: true // (default) }); const result = parser.parse(xmlString, true); // true for validation, -v ``` -------------------------------- ### Filter Tags for Entity Replacement Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/callbacks.md Use tagFilter to specify which tags should have entities replaced. This example replaces entities only in 'description', 'content', and 'notes' tags. ```javascript const options = { processEntities: { enabled: true, tagFilter: (tagName, jPath) => { // Only replace in safe tags const safeTags = ['description', 'content', 'notes']; return safeTags.includes(tagName); } } }; ``` -------------------------------- ### Entity Replacement During Tag Value Processing Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/Entities.md Configure `tagValueProcessor` to receive values with entities already replaced. For example, `©` becomes `©` before the callback. ```javascript const options = { tagValueProcessor: (tag, val) => { // val already has entities replaced // "©" has already become "©" console.log(val); return val; } }; ``` -------------------------------- ### Creating Path Expressions Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Demonstrates how to create compiled Expression objects for various path matching scenarios. This includes simple paths, deep wildcards, attribute conditions, position selectors, complex patterns, and custom separators. ```javascript import { Expression } from 'fast-xml-parser'; // Simple path const expr1 = new Expression('root.users.user'); // Deep wildcard - match at any depth const expr2 = new Expression('..config'); // With attributes const expr3 = new Expression('user[id]'); const expr4 = new Expression('user[id=admin123]'); // With positions const expr5 = new Expression('item:first'); const expr6 = new Expression('item:last'); // Complex patterns const expr7 = new Expression('root.data..item[type=special]:first'); // Custom separator const expr8 = new Expression('root/users/user', { separator: '/' }); ``` -------------------------------- ### Transform Tag Values Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/README.md Transform tag values using the `tagValueProcessor`. This example converts a 'timestamp' tag's value into an ISO string format. ```javascript const options = { tagValueProcessor: (tagName, value) => { if (tagName === 'timestamp') { return new Date(value).toISOString(); } return value; } }; ``` -------------------------------- ### XmlBuilderOptions Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/types.md Configuration for XML building. ```APIDOC ## XmlBuilderOptions ### Description Configuration for XML building. ### Type Definition ```typescript type XmlBuilderOptions = { attributeNamePrefix?: string; attributesGroupName?: false | string; textNodeName?: string; ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean); cdataPropName?: false | string; commentPropName?: false | string; format?: boolean; indentBy?: string; arrayNodeName?: string; suppressEmptyNode?: boolean; suppressUnpairedNode?: boolean; suppressBooleanAttributes?: boolean; preserveOrder?: boolean; unpairedTags?: string[]; stopNodes?: JPathOrExpression[]; tagValueProcessor?: (name: string, value: unknown) => unknown; attributeValueProcessor?: (name: string, value: unknown) => unknown; processEntities?: boolean; maxNestedTags?: number; } ``` ``` -------------------------------- ### Getting Node Sibling Position Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Illustrates using `getPosition` to identify the sibling position (1-indexed) of the current node, useful for targeting the first or subsequent siblings. ```javascript tagValueProcessor: (tag, val, matcher) => { const position = matcher.getPosition(); if (position === 1) { // First item in parent } return val; } ``` -------------------------------- ### Optimizing Tag Value Processor with Early Return Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/callbacks.md Illustrates an efficient way to use tagValueProcessor by returning early for tags that do not require processing. This avoids unnecessary computations and improves performance. ```javascript // GOOD: Simple early return const options = { tagValueProcessor: (tag, val) => { if (tag !== 'price') return undefined; return parseFloat(val); } }; ``` -------------------------------- ### Instantiate XMLBuilder Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/XMLBuilder.md Create a new XMLBuilder instance. An empty constructor uses default options. Custom options can be provided to configure builder behavior. ```javascript // Basic builder const builder = new XMLBuilder(); const xml = builder.build({ root: { item: 'text' } }); ``` ```javascript // With custom options const builder = new XMLBuilder({ format: true, indentBy: ' ', attributeNamePrefix: '@_', ignoreAttributes: false }); const xml = builder.build(jsObject); ``` -------------------------------- ### Ignore Attributes with Matcher Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/callbacks.md Combine ignoreAttributes with a Matcher to conditionally ignore attributes. This example ignores 'debug_' attributes unless they are within the '..config' path. ```javascript const options = { jPath: false, ignoreAttributes: (attrName, matcher) => { // Ignore debug attrs except in config if (attrName.startsWith('debug_')) { return !matcher.matches(new Expression('..config')); } return false; } }; ``` -------------------------------- ### Recommended Migration for XMLBuilder Import Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/XMLBuilder.md This class re-exports from `fast-xml-builder`. In future versions, this may be completely removed from `fast-xml-parser`. Use the new import path for recommended migration. ```javascript // Old way (deprecated) import { XMLBuilder } from 'fast-xml-parser'; const builder = new XMLBuilder(options); const xml = builder.build(jsObject); // New way (recommended) import XMLBuilder from 'fast-xml-builder'; const builder = new XMLBuilder(options); const xml = builder.build(jsObject); ``` -------------------------------- ### Initialize XML Parser and Builder Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/index.html Initializes the XMLParser and XMLBuilder from the fxp library. Used for parsing XML to JSON and building XML from JSON respectively. ```javascript const parser = new fxp.XMLParser(buildParsingConfig()); const builder = new fxp.XMLBuilder(xmlBuilderOptions()); ``` -------------------------------- ### Selective Entity Replacement with processEntities Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Control entity replacement by defining a tagFilter within processEntities. This example enables entity replacement only for elements within a 'config' path. ```javascript const options = { processEntities: { enabled: true, tagFilter: (tagName, matcher) => { // Only replace entities in safe tags const path = matcher.toString(); const inConfig = matcher.matches(new Expression('..config')); return inConfig; } } }; ``` -------------------------------- ### Attribute Processing Error Handling Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/errors.md Shows an example of an attributeValueProcessor where errors can propagate to the caller. This snippet includes a potential Date parsing error that could throw a RangeError. ```javascript const options = { attributeValueProcessor: (attrName, val) => { // Errors here propagate to caller if (val === 'PARSE_DATE') { return new Date(val).toISOString(); // May throw RangeError } return val; } }; ``` -------------------------------- ### Prevent Prototype Pollution with Configuration Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/errors.md Illustrates how Fast-XML-Parser's configuration options prevent prototype pollution attacks by throwing errors when dangerous property names like '__proto__' or 'constructor' are used. ```javascript const options = { attributeNamePrefix: '__proto__' // Error: "[SECURITY] Invalid attributeNamePrefix: \"__proto__\" is a reserved..." }; ``` ```javascript const options = { textNodeName: 'constructor' // Error: "[SECURITY] Invalid textNodeName: \"constructor\" is a reserved..." }; ``` -------------------------------- ### Parse XML with DOCTYPE Entities Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/Entities.md The parser automatically resolves entities defined within the DOCTYPE declaration of an XML document. No explicit setup is required for DOCTYPE entities. ```xml ]> &company; Manual v&version; ``` ```javascript const parser = new XMLParser(); const result = parser.parse(xmlString); // { book: { title: 'Acme Corp Manual v1.0' } } ``` -------------------------------- ### CLI Options: Parsing Behavior Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md Control parsing behavior with options like preserving namespace prefixes, ignoring attributes, or keeping all values as strings. ```bash -ns ``` ```bash -a ``` ```bash -c ``` -------------------------------- ### Publish Legacy Version Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/docs/CHECK_LIST.md Publish a legacy version of the package using a specific tag. ```bash npm publish --tag legacy ``` -------------------------------- ### Build XML Builder Options Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/index.html Defines default options for the XML builder, including prefixes for attributes and group names. These options can be customized via UI elements. ```javascript function xmlBuilderOptions(){ const defaultOptions = { attributeNamePrefix : "@_", attributesGroupName: $("#attributesGroupName").prop("checked") ? "@" : false, textNodeName : "#text", ignoreAttributes : $("#ignoreAttributes").prop("checked"), cdataTagName: ``` -------------------------------- ### Getting Node Nesting Depth Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Shows how to use `getDepth` to retrieve the current nesting depth of the XML node, useful for enforcing limits or conditional logic based on hierarchy. ```javascript tagValueProcessor: (tag, val, matcher) => { const depth = matcher.getDepth(); if (depth > 10) { throw new Error('Too deeply nested'); } return val; } ``` -------------------------------- ### Modify Attributes with updateTag Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/callbacks.md Modify attributes in place using the updateTag option. This example demonstrates removing specific internal attributes like '@_internal' and '@_debug' before the tag is processed. ```js const options = { updateTag: (tagName, jPath, attrs) => { // Remove internal attributes delete attrs['@_internal']; delete attrs['@_debug']; return tagName; // Keep tag, attributes modified in place } }; ``` -------------------------------- ### Build Parsing Configuration Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/index.html Constructs a configuration object for the XML parser based on various UI options. This allows customization of parsing behavior. ```javascript function buildParsingConfig(){ const config = { alwaysCreateTextNode: $("#alwaysCreateTextNode").prop("checked"), attributeNamePrefix : "@_", attributesGroupName: $("#attributesGroupName").prop("checked") ? "@" : false, textNodeName : "#text", ignoreAttributes : $("#ignoreAttributes").prop("checked"), ignoreDeclaration: $("#ignoreDeclaration").prop("checked"), removeNSPrefix : $("#removeNSPrefix").prop("checked"), parseNodeValue : $("#parseNodeValue").prop("checked"), parseAttributeValue : $("#parseAttributeValue").prop("checked"), allowBooleanAttributes: $("#allowBooleanAttributes").prop("checked"), trimValues: $("#trimValues").prop("checked"), //Trim string values of tag and attributes cdataTagName: $("#parseCDATA").prop("checked") ? "#cdata" : false, preserveOrder: $("#preserveOrder").prop("checked"), numberParseOptions: { hex: false, leadingZeros: $("#leadingZeros").prop("checked") } }; return config; } ``` -------------------------------- ### Skip Deprecated Elements with updateTag Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Implement custom logic to skip processing of specific elements by returning false from the updateTag function. This example skips tags that have a 'deprecated' attribute. ```javascript const options = { jPath: false, updateTag: (tagName, matcher, attrs) => { if (matcher.hasAttr('deprecated')) { console.warn(`Skipping deprecated tag: ${tagName}`); return false; // Skip this tag } return tagName; } }; ``` -------------------------------- ### Independent Parser Instances for Recoverable Scenarios Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/errors.md Illustrates how to manage potentially failing parsing operations by using separate parser instances for different data inputs, ensuring that a failure in one does not affect others. ```javascript // Recoverable - different parser instance const parser1 = new XMLParser(optionsA); const result1 = parser1.parse(data1); // May fail const parser2 = new XMLParser(optionsB); const result2 = parser2.parse(data2); // Independent ``` -------------------------------- ### Get Metadata Symbol Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/XMLParser.md Retrieve the static Symbol or string property name used for accessing metadata attached to parsed XML nodes. Metadata is captured when `captureMetaData: true` is set. ```javascript const parser = new XMLParser({ captureMetaData: true }); const result = parser.parse(xmlData); const metaDataSymbol = XMLParser.getMetaDataSymbol(); // Access metadata on a parsed node const metadata = result.root[metaDataSymbol]; if (metadata?.startIndex !== undefined) { console.log('Node started at character:', metadata.startIndex); } ``` -------------------------------- ### Filter Tags with Matcher for Entity Replacement Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/callbacks.md Utilize tagFilter with a Matcher to conditionally replace entities. This example allows entity replacement unless the element matches the '..config' expression. ```javascript const options = { jPath: false, processEntities: { enabled: true, tagFilter: (tagName, matcher) => { // Allow entities in user content, not config return !matcher.matches(new Expression('..config')); } } }; ``` -------------------------------- ### Import XMLParser in Browser via CDN Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/README.md Include the Fast XML Parser library in a web browser environment using a Content Delivery Network (CDN). ```html ``` -------------------------------- ### Conditional Attribute Processing with attributeValueProcessor Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Use attributeValueProcessor to conditionally process attribute values based on the attribute name and other context. This example parses attribute values as integers only for 'admin' roles. ```javascript const options = { jPath: false, attributeValueProcessor: (name, val, matcher) => { // Only parse as number for admin attributes if (name === 'permissions') { const role = matcher.getAttrValue('role'); if (role === 'admin') { return parseInt(val, 2); // Parse as binary } } return val; } }; ``` -------------------------------- ### Safe Configuration for Untrusted Input Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/Entities.md Provides a sample configuration for parsing untrusted XML input with enhanced security. This includes minimal entity processing, disabling HTML entities, limiting nested tags, and enforcing strict reserved names. ```javascript const options = { // Minimal entity processing processEntities: { enabled: true, maxEntityCount: 5, maxEntitySize: 500, maxTotalExpansions: 10, maxExpandedLength: 5000, // Only allow in safe tags allowedTags: ['description', 'content', 'notes'] }, htmlEntities: false, // No HTML entities maxNestedTags: 20, // Shallow nesting strictReservedNames: true }; const parser = new XMLParser(options); ``` -------------------------------- ### Using Expression Objects in stopNodes Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Define nodes to stop parsing at using an array of Expression objects or string patterns in the stopNodes option. This example prevents parsing of script and style tags, and specific database elements. ```javascript import { Expression } from 'fast-xml-parser'; const options = { stopNodes: [ new Expression('..script'), // Don't parse script tags new Expression('..style'), // Don't parse style tags new Expression('root.database[type]'), // Don't parse databases with type attr '..raw' // String patterns also work ] }; ``` -------------------------------- ### Enable Entity Processing (Default) Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/Entities.md Configures the parser to process XML entities, which is the default behavior. ```javascript // Enable (default) const options = { processEntities: true }; ``` -------------------------------- ### Use Matcher Mode with updateTag Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/callbacks.md Leverage Matcher mode in updateTag to control parsing based on node depth or complex expressions. This example skips nodes exceeding a depth of 10 and internal configuration sections matching a specific expression. ```js const options = { jPath: false, updateTag: (tagName, matcher, attrs) => { // Skip nodes too deep if (matcher.getDepth() > 10) { return false; } // Skip internal config sections if (matcher.matches(new Expression('..config[internal=true]'))) { return false; } return tagName; } }; ``` -------------------------------- ### MatcherView Usage in Callbacks Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/types.md Demonstrates how to use the MatcherView instance within the tagValueProcessor callback to access current path information, attributes, and apply conditional logic based on expressions. ```typescript const options = { jPath: false, // Enable Matcher mode tagValueProcessor: (tag, val, matcher) => { // matcher is a MatcherView instance const isAdmin = matcher.getAttrValue('role') === 'admin'; const depth = matcher.getDepth(); const tag = matcher.getCurrentTag(); if (matcher.matches(new Expression("..user[status=active]"))) { // Process active users at any depth } return val; } }; ``` -------------------------------- ### Backward Compatibility for stopNodes Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Demonstrates the conversion of old-style stopNodes with '*.tagname' format to the new '..tagname' syntax. The old syntax is still supported but the new syntax is preferred. ```javascript // Old syntax (still supported) const options = { stopNodes: ['*.config'] // Treated as ..config }; // New syntax (preferred) const options = { stopNodes: ['..config'] }; ``` -------------------------------- ### Initialize CodeMirror Editor Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/index.html Initializes the CodeMirror editor for XML editing. It sets up various options like mode, line numbers, and gutter for folding. ```javascript editor = CodeMirror.fromTextArea(document.getElementById("txtXml"), { mode: "application/xml", styleActiveLine: true, lineNumbers: true, foldGutter: true, autofocus: true, gutters: ["CodeMirror-foldgutter"] }); ``` -------------------------------- ### Expression Compilation Optimization Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Shows the recommended practice of compiling PathExpressions once and reusing them, especially within callbacks. Avoids performance overhead by preventing repeated compilation of the same expression. ```javascript // GOOD: Compile once, reuse const adminExpr = new Expression('..user[role=admin]'); const options = { tagValueProcessor: (tag, val, matcher) => { if (matcher.matches(adminExpr)) { /* ... */ } return val; } }; // AVOID: Compiling in callback const options = { tagValueProcessor: (tag, val, matcher) => { // BAD - new Expression created per tag! if (matcher.matches(new Expression('..user'))) { /* ... */ } return val; } }; ``` -------------------------------- ### Run parser benchmarks Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/benchmark/README.md Execute only the parser-specific benchmarks. ```shell $ npm run parser ``` -------------------------------- ### Import XMLParser Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/XMLParser.md Import the XMLParser class for use in your project. Supports both ES Modules and CommonJS. ```javascript import { XMLParser } from 'fast-xml-parser'; // or CommonJS const { XMLParser } = require('fast-xml-parser'); ``` -------------------------------- ### Expression Object Properties and Methods Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/PathExpression.md Demonstrates the properties and methods available on a compiled Expression object. This includes accessing the original pattern, separator, segments, and checking for specific features like deep wildcards or attribute conditions. ```javascript const expr = new Expression('root.users.user[id]:last'); expr.pattern; // "root.users.user[id]:last" expr.separator; // "." expr.segments; // Array of Segment objects expr.length; // 3 expr.hasDeepWildcard(); // false expr.hasAttributeCondition(); // true (id attribute) expr.hasPositionSelector(); // true (:last) expr.toString(); // "root.users.user[id]:last" ``` -------------------------------- ### XMLParser Constructor Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/XMLParser.md Creates a new XML parser instance with configurable options to control parsing behavior. ```APIDOC ## XMLParser Constructor ### Description Creates a new XML parser instance with the given configuration options. ### Signature ```javascript constructor(options?: X2jOptions): XMLParser ``` ### Parameters #### options - **options** (X2jOptions) - Optional - Configuration object for parser behavior. See [Configuration](../configuration.md) for all available options. ### Example ```javascript // Basic parsing const parser = new XMLParser(); const result = parser.parse('text'); // With custom options const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_', parseTagValue: true, preserveOrder: false }); const result = parser.parse(xmlData); ``` ``` -------------------------------- ### strnumOptions Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/types.md Configuration for number parsing. ```APIDOC ## strnumOptions ### Description Configuration for number parsing. ### Type Definition ```typescript type strnumOptions = { hex: boolean; leadingZeros: boolean; skipLike?: RegExp; eNotation?: boolean; infinity?: string; unicode?: boolean; } ``` ``` -------------------------------- ### XMLBuilder Constructor Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/XMLBuilder.md Creates a new XML builder instance with the given configuration options. This class is deprecated. ```APIDOC ## XMLBuilder(options) ### Description Creates a new XML builder instance with the given configuration options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (XmlBuilderOptions) - Optional - Configuration object for builder behavior. See Configuration section below. ### Request Example ```javascript // Basic builder const builder = new XMLBuilder(); const xml = builder.build({ root: { item: 'text' } }); // With custom options const builder = new XMLBuilder({ format: true, indentBy: ' ', attributeNamePrefix: '@_', ignoreAttributes: false }); const xml = builder.build(jsObject); ``` ### Response None ### Throws None explicitly documented for constructor. ``` -------------------------------- ### Managing State with Tag Value Processor Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/callbacks.md Shows how to maintain state across multiple calls to a tagValueProcessor by using an external object. This is necessary because callbacks are stateless by default. ```javascript const state = {}; const options = { tagValueProcessor: (tag, val) => { // Accumulate state during parsing if (!state[tag]) state[tag] = []; state[tag].push(val); return val; } }; const result = parser.parse(xmlData); console.log(state); // Contains accumulated data ``` -------------------------------- ### Chain XML Parsing with jq Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/cli.md This command pipes the JSON output of an XML file to jq for further transformation, specifically extracting the name from the first user in the 'users' array. ```bash fxparser data.xml | jq '.root.users[0].name' ``` -------------------------------- ### Import XMLBuilder Source: https://github.com/naturalintelligence/fast-xml-parser/blob/master/_autodocs/api-reference/XMLBuilder.md Import the XMLBuilder class from the 'fast-xml-parser' library. Supports both ES module and CommonJS syntax. ```javascript import { XMLBuilder } from 'fast-xml-parser'; // or CommonJS const { XMLBuilder } = require('fast-xml-parser'); ```