### Install Dependencies and Run Tests Source: https://github.com/nashwaan/xml-js/blob/master/README.md Use these commands to set up the project locally and run the test suite. For live testing, replace 'npm test' with 'npm start'. ```bash cd xml-js npm install npm test ``` -------------------------------- ### Browserify Installation and Bundling Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/module-exports.md Install the xml-js package using npm and then bundle it using Browserify. ```bash # Install and bundle npm install xml-js browserify -r xml-js > bundle.js ``` -------------------------------- ### Install xml-js Library and CLI Tool Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/README.md Install xml-js as a dependency for your project or as a global command-line tool. ```bash # As a library npm install --save xml-js ``` ```bash # As a CLI tool npm install -g xml-js ``` -------------------------------- ### Install xml-js globally Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/README.md Install the xml-js package globally using npm to enable the command-line interface. ```bash # Global installation npm install -g xml-js ``` -------------------------------- ### XML to JS/JSON Compact Conversion Samples Source: https://github.com/nashwaan/xml-js/blob/master/README.md Examples showing various XML inputs and their corresponding compact JSON outputs. ```json {"a":{}} ``` ```json {"a":{},"b":{}} ``` ```json {"a":{"b":{}}} ``` ```json {"a":{"_text":" Hi "}} ``` ```json {"a":{"_attributes":{"x":"1.234","y":"It's"}}} ``` ```json {"_declaration":{}} ``` ```json {"_instruction":{"go":"there"}} ``` ```json {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}}} ``` ```json {"_comment":"Hello, World!"} ``` ```json {"_cdata":""} ``` -------------------------------- ### Install xml-js Locally Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Install the xml-js package as a project dependency for use within npm scripts. ```bash npm install --save xml-js ``` -------------------------------- ### Rollup Configuration for xml-js Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/module-exports.md Example Rollup configuration file demonstrating how to include the xml-js library. ```javascript // rollup.config.js import resolve from '@rollup/plugin-node-resolve'; export default { input: 'src/index.js', plugins: [resolve()], external: [] }; ``` -------------------------------- ### Display Version Information Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Use the `--version` or `-v` flags to display the installed version of the `xml-js` package. ```bash xml-js --version ``` ```bash xml-js -v ``` -------------------------------- ### Compact JSON Format Example Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/README.md Demonstrates the compact JSON output format where element names are used as keys, optimizing for readability. ```javascript { root: { ... } } ``` -------------------------------- ### Convert Files Using Global Command Source: https://github.com/nashwaan/xml-js/blob/master/README.md Use the globally installed 'xml-js' command to convert files. Specify input and output files, and indentation spaces. ```bash xml-js test.json --spaces 4 xml-js test.json --spaces 4 --out test.xml xml-js test.xml --spaces 4 xml-js test.xml --spaces 4 --out test.json ``` -------------------------------- ### Example ElementCompact Object Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/types.md This example demonstrates how to construct an ElementCompact object. It shows a root element with an attribute and two child elements, one containing text. ```typescript const compact: ElementCompact = { root: { _attributes: { id: "1" }, user: { _text: "Alice" }, age: { _text: "30" } } }; // Represents: Alice30 ``` -------------------------------- ### XML to JS/JSON Non-Compact Conversion Samples Source: https://github.com/nashwaan/xml-js/blob/master/README.md Examples showing various XML inputs and their corresponding non-compact JSON outputs. ```json {"elements":[{"type":"element","name":"a"}]} ``` ```json {"elements":[{"type":"element","name":"a"},{"type":"element","name":"b"}]} ``` ```json {"elements":[{"type":"element","name":"a","elements":[{"type":"element","name":"b"}]}]} ``` ```json {"elements":[{"type":"element","name":"a","elements":[{"type":"text","text":" Hi "}]}]} ``` ```json {"elements":[{"type":"element","name":"a","attributes":{"x":"1.234","y":"It's"}}]} ``` ```json {"declaration":{}} ``` ```json {"elements":[{"type":"instruction","name":"go","instruction":"there"}]} ``` ```json {"declaration":{"attributes":{"version":"1.0","encoding":"utf-8"}}} ``` ```json {"elements":[{"type":"comment","comment":"Hello, World!"}]} ``` ```json {"elements":[{"type":"cdata","cdata":""}]} ``` -------------------------------- ### Convert and Save to File Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Use the `--out` option to specify an output file path for saving the conversion result. This example converts XML to JSON. ```bash xml-js input.xml --out output.json ``` -------------------------------- ### XML-JS Option Validation Example Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/architecture.md Demonstrates the normalization of user-provided options within `validateOptions()`. It shows how initial options are expanded with default flags, validated key names, and checked for callback function existence. ```javascript // Before { trim: true, nativeType: true } // After validation { trim: true, nativeType: true, sanitize: false, compact: false, addParent: false, // ... all other flags with defaults declarationKey: 'declaration', instructionKey: 'instruction', // ... all key names with defaults textFn: undefined, // No callbacks // ... other options } ``` -------------------------------- ### Pretty-Print XML with Spaces Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/api-reference-js2xml.md This example shows how to generate pretty-printed XML with a specified number of spaces for indentation. Use the `spaces` option with a number to control the indentation level. ```javascript const convert = require('xml-js'); const obj = { root: { user: { _text: 'Alice' }, age: { _text: '30' } } }; const xml = convert.js2xml(obj, { compact: true, spaces: 2 }); // Result: // // Alice // 30 // ``` -------------------------------- ### Compact JSON Data Format Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/quick-reference.md Example of the JSON structure when `compact: true` is used. ```json { "_declaration": { "_attributes": { "version": "1.0" } }, "root": { "_attributes": { "id": "1" }, "child": { "_text": "content" } } } ``` -------------------------------- ### Non-Compact JSON Format Example Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/README.md Illustrates the default non-compact JSON output format, which includes explicit type information and preserves element order. ```javascript { elements: [ { type: 'element', name: 'root', elements: [...] } ] } ``` -------------------------------- ### Non-Compact JSON Data Format Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/quick-reference.md Example of the JSON structure when `compact: false` is used. ```json { "declaration": { "attributes": { "version": "1.0" } }, "elements": [ { "type": "element", "name": "root", "attributes": { "id": "1" }, "elements": [ { "type": "element", "name": "child", "elements": [ { "type": "text", "text": "content" } ] } ] } ] } ``` -------------------------------- ### Convert Compact JavaScript Object to XML Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/api-reference-js2xml.md This example demonstrates converting a compact JavaScript object format to XML. Use this when your object uses keys for element names and special properties like `_text` for content. ```javascript const convert = require('xml-js'); const obj = { note: { title: { _text: 'Hello' }, body: { _text: 'World' } } }; const xml = convert.js2xml(obj, { compact: true }); // Result: HelloWorld ``` -------------------------------- ### Writing: Apply custom formatting to text Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/configuration.md Customize text formatting during XML writing using the `textFn` callback. This example trims whitespace and converts text to uppercase before writing. ```javascript js2xml(obj, { textFn: function(text, elementName, elementObj) { return text.trim().toUpperCase(); } }); ``` -------------------------------- ### Example Usage of DeclarationAttributes Interface Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/types.md Create an object conforming to the `DeclarationAttributes` interface, specifying optional properties like version, encoding, and standalone status for an XML declaration. ```typescript const declAttrs: DeclarationAttributes = { version: "1.0", encoding: "utf-8", standalone: "no" }; ``` -------------------------------- ### Create an XML Element Object (TypeScript) Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/types.md Example of creating an Element object that represents a simple XML structure with attributes and nested elements. This demonstrates how to populate the Element interface for use with xml-js. ```typescript const element: Element = { type: "element", name: "person", attributes: { id: "1" }, elements: [ { type: "element", name: "name", elements: [ { type: "text", text: "Alice" } ] }, { type: "element", name: "age", elements: [ { type: "text", text: "30" } ] } ] }; // Represents: Alice30 ``` -------------------------------- ### Display Help Information Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Use the `--help` or `-h` flags to display all available command-line options and their descriptions. ```bash xml-js --help ``` ```bash xml-js -h ``` -------------------------------- ### CLI Usage Help Source: https://github.com/nashwaan/xml-js/blob/master/README.md Displays the help content for the xml-js command-line interface, outlining usage and available options. ```bash Usage: xml-js src [options] src Input file that need to be converted. Conversion type xml->json or json->xml will be inferred from file extension. Options: --help, -h Display this help content. --version, -v Display version number of this module. --out Output file where result should be written. --spaces Specifies amount of space indentation in the output. --full-tag XML elements will always be in form. --no-decl Declaration directive will be ignored. --no-inst Processing instruction will be ignored. --no-attr Attributes of elements will be ignored. --no-text Texts of elements will be ignored. --no-cdata CData of elements will be ignored. --no-doctype DOCTYPE of elements will be ignored. --no-comment Comments of elements will be ignored. --trim Any whitespaces surrounding texts will be trimmed. --compact JSON is in compact form. --native-type Numbers and boolean will be converted (coerced) to native type instead of text. --always-array Every element will always be an array type (applicable if --compact is set). --always-children Every element will always contain sub-elements (applicable if --compact is not set). --text-key To change the default 'text' key. --cdata-key To change the default 'cdata' key. --doctype-key To change the default 'doctype' key. --comment-key To change the default 'comment' key. --attributes-key To change the default 'attributes' key. --declaration-key To change the default 'declaration' key. --instruction-key To change the default 'processing instruction' key. --type-key To change the default 'type' key (applicable if --compact is not set). --name-key To change the default 'name' key (applicable if --compact is not set). --elements-key To change the default 'elements' key (applicable if --compact is not set). ``` -------------------------------- ### Convert with CLI Options Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/quick-reference.md Use the `xml-js` command-line tool with multiple options like `--compact`, `--trim`, and `--native-type`. ```bash # With options xml-js input.xml --compact --trim --native-type ``` -------------------------------- ### CLI conversion with custom options Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/README.md Apply custom conversion options like `--compact`, `--trim`, `--native-type`, and `--no-comment` directly from the command line. ```bash # With custom options xml-js data.xml --compact --trim --native-type --no-comment ``` -------------------------------- ### Run npm script Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Execute the configured npm script to perform the XML to JSON conversion. ```bash npm run convert ``` -------------------------------- ### Configure Size Optimization Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/quick-reference.md Optimize output size by using options like `compact: true` and `spaces: 0` for minified output. You can also skip unnecessary components like comments and declarations. ```javascript // Minified output { compact: true, spaces: 0 } // Compact format (not non-compact) { compact: true } // Skip unnecessary components { ignoreComment: true, ignoreDeclaration: true } ``` -------------------------------- ### Example Usage of Attributes Interface Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/types.md Instantiate the `Attributes` interface with string, number, and undefined values to represent XML attributes. Note that `undefined` values are omitted during XML writing. ```typescript const attrs: Attributes = { id: "123", version: 1, optional: undefined // Will be omitted during XML write }; ``` -------------------------------- ### Module Organization Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/architecture.md Illustrates the directory structure of the xml-js library, highlighting the purpose of key directories and files. ```tree xml-js/ ├── lib/ │ ├── index.js Export public API (4 functions) │ ├── xml2js.js Parse XML to JS object │ ├── xml2json.js Parse XML to JSON string │ ├── js2xml.js Convert JS object to XML │ ├── json2xml.js Parse JSON and convert to XML │ ├── options-helper.js Validate and prepare options │ └── array-helper.js Cross-browser array checking ├── types/ │ └── index.d.ts TypeScript type definitions ├── bin/ │ └── cli.js Command-line interface └── test/ └── ... Test files ``` -------------------------------- ### Configure npm script for Conversion Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Define a script in `package.json` to easily run the `xml-js` conversion command with specified options. ```json { "scripts": { "convert": "xml-js input.json --spaces 4" } } ``` -------------------------------- ### Parsing Options Flow Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/architecture.md Outlines the sequence of operations when parsing raw XML into a JavaScript object. This includes option validation, SAX parser setup, and applying various transformations and callbacks to parsed elements. ```text Raw XML ↓ parse(xml, userOptions) ├─ validateOptions(userOptions) │ └─ Merge defaults, validate, normalize ├─ Setup SAX parser with validated options └─ For each parsed element: ├─ Apply ignore options (ignoreText, ignoreComment, etc.) ├─ Apply transformation options (trim, nativeType, etc.) ├─ Apply callback functions (textFn, elementNameFn, etc.) └─ Format according to compact option ``` -------------------------------- ### Specify Input File Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md The `` argument is the required input file path for the conversion process. ```bash xml-js ``` -------------------------------- ### XML to JSON with Custom Element Name Processing Source: https://github.com/nashwaan/xml-js/blob/master/README.md Use `elementNameFn` to transform element names during XML to JSON conversion. This example renames 'foo:Name' to 'NAME'. Ensure `compact` is set to `true` for this functionality. ```javascript var convert = require('xml-js'); var xml = 'Ali 30'; var options = {compact: true, elementNameFn: function(val) {return val.replace('foo:','').toUpperCase();}}; var result = convert.xml2json(xml, options); console.log(result); // {"NAME":{"_text":"Ali"},"BAR:AGE":{"_text":"30"}} ``` -------------------------------- ### Convert and Print to Console Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Convert the input XML file and print the resulting JSON directly to the standard output. ```bash xml-js input.xml ``` -------------------------------- ### Verbose JSON Output with Details Configuration Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/configuration.md Use this configuration to include all details in the JSON output, such as always including child elements. ```javascript { compact: false, spaces: 2, alwaysChildren: true } ``` -------------------------------- ### JSON to XML with Custom Text Node Processing Source: https://github.com/nashwaan/xml-js/blob/master/README.md Use `textFn` to modify text content during JSON to XML conversion. This example appends an empty string to the text of the 'age' element, effectively ensuring it's treated as a string. ```javascript var convert = require('xml-js'); var json = '{"name":{"_text":"Ali"},"age":{"_text":"30"}}'; var options = {compact: true, textFn: function(val, elementName) {return elementName === 'age'? val + '';}}; var result = convert.json2xml(json, options); console.log(result); // Ali 30 ``` -------------------------------- ### Conversion Cheat Sheet Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/quick-reference.md A summary of common xml-js conversion tasks, including parsing XML to JS, generating XML from JS, and converting via JSON. Demonstrates basic formatting and type conversion options. ```javascript // Parse XML const obj = convert.xml2js(xml, { compact: true }); // Generate XML const xml = convert.js2xml(obj, { compact: true, spaces: 2 }); // Convert via JSON const json = convert.xml2json(xml, { compact: true }); const xml = convert.json2xml(json, { compact: true }); // Format options { spaces: 0 } // Minified { spaces: 2 } // 2-space indent { spaces: '\t' } // Tab indent // Type conversion { nativeType: true, trim: true } // "123" → 123, " text " → "text" // Attribute handling { _attributes: { id: '1', value: 123 } } // ``` -------------------------------- ### Indent Processing Instructions with 'indentInstruction' Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/configuration.md When true and 'spaces' is not 0, places processing instructions on new lines with indentation. Defaults to false. ```javascript // This option is a boolean and does not have a direct code example shown here, but it affects the formatting of processing instructions. ``` -------------------------------- ### Package.json Entry Points for xml-js Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/module-exports.md Defines the main, types, and binary entry points for the xml-js package, specifying how the library is loaded in different environments (CommonJS, TypeScript) and how the CLI is accessed. ```json { "main": "lib/index.js", "types": "types/index.d.ts", "bin": "./bin/cli.js" } ``` -------------------------------- ### TypeScript Import with Options Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/module-exports.md Import functions and types from xml-js in TypeScript, demonstrating how to pass options to conversion functions. ```typescript // With options const options: Options.XML2JS = { compact: true, spaces: 2 }; ``` -------------------------------- ### Read JSON File and Convert to XML Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/api-reference-json2xml.md Demonstrates reading a JSON file using fs.readFileSync and then converting it to XML using the json2xml function. Ensure the 'compact' option matches the input structure format. ```javascript const fs = require('fs'); const json = fs.readFileSync('data.json', 'utf8'); const xml = convert.json2xml(json, { compact: true, spaces: 2 }); ``` -------------------------------- ### xml-js Core Function Usages Source: https://github.com/nashwaan/xml-js/blob/master/README.md Demonstrates the basic usage of the four main conversion functions provided by the xml-js library. Ensure the library is required before use. ```javascript var convert = require('xml-js'); result = convert.js2xml(js, options); // to convert javascript object to xml text result = convert.json2xml(json, options); // to convert json text to xml text result = convert.xml2js(xml, options); // to convert xml text to javascript object result = convert.xml2json(xml, options); // to convert xml text to json text ``` -------------------------------- ### Configure Output Indentation with 'spaces' Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/configuration.md Controls indentation in the output. Use 0 for minified output, a number for space indentation, or a string (like '\t') for tab indentation. ```javascript // spaces: 0 (default) text // spaces: 2 text // spaces: '\t' text ``` -------------------------------- ### Type-safe Options for xml-js Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/README.md Shows how to use TypeScript for type-safe configuration options when converting XML. Import the Options type and specify the desired configuration interface, such as Options.XML2JS. ```typescript // Type-safe options import { Options } from 'xml-js'; const opts: Options.XML2JS = { trim: true }; ``` -------------------------------- ### XML to JSON with Custom Key Names Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/api-reference-xml2json.md Illustrates how to customize the key names used in the JSON output for text content and elements. This is achieved using 'textKey' and 'elementsKey' options. ```javascript const convert = require('xml-js'); const xml = 'content'; const result = convert.xml2json(xml, { textKey: 'value', elementsKey: 'children' }); // Custom key names appear in the JSON output ``` -------------------------------- ### Compact vs. Non-Compact XML to JSON Conversion Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/usage-patterns.md Demonstrates the difference between default (non-compact) and compact JSON output formats when converting XML to JSON. Use non-compact for explicit type information and compact for a more streamlined structure. ```javascript const convert = require('xml-js'); const xml = 'text'; // Non-compact (default): explicit type information const nonCompact = convert.xml2js(xml); console.log(JSON.stringify(nonCompact, null, 2)); // { // "elements": [ // { // "type": "element", // "name": "root", // "elements": [ // { // "type": "element", // "name": "child", // "attributes": { // "attr": "value" // }, // "elements": [ // { // "type": "text", // "text": "text" // } // ] // } // ] // } // ] // } // Compact: element names as keys const compact = convert.xml2js(xml, { compact: true }); console.log(JSON.stringify(compact, null, 2)); // { // "root": { // "child": { // "_attributes": { // "attr": "value" // }, // "_text": "text" // } // } // } ``` -------------------------------- ### Configure npm Script for xml-js Source: https://github.com/nashwaan/xml-js/blob/master/README.md Add a script to your package.json to easily run xml-js conversions. This is useful for task automation. ```json ... "dependencies": { "xml-js": "latest" }, "scripts": { "convert": "xml-js test.json --spaces 4" } ... ``` -------------------------------- ### Convert JSON to XML via CLI Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/quick-reference.md Use the `xml-js` command-line tool to convert a JSON file to XML, specifying an output file and pretty-printing. ```bash # JSON to XML xml-js file.json --spaces 2 --out output.xml ``` -------------------------------- ### Pretty-Printed JSON Output Configuration Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/configuration.md Use this configuration for a human-readable JSON output with indentation. ```javascript { compact: true, spaces: 2, trim: true } ``` -------------------------------- ### Key Naming Options Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/quick-reference.md Options to customize property names for text, attributes, CDATA, and comments. ```APIDOC ## Key Naming Options | Option | Default (compact) | Default (non-compact) | Purpose | |--------|-------------------|----------------------|---------| | textKey | _text | text | Property name for element text | | attributesKey | _attributes | attributes | Property name for attributes | | cdataKey | _cdata | cdata | Property name for CDATA | | commentKey | _comment | comment | Property name for comments | ``` -------------------------------- ### Command Line Interface for XML/JSON Conversion Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/README.md Perform XML to JSON and JSON to XML conversions using the xml-js CLI tool. Supports options for formatting and output files. ```bash # XML to JSON xml-js input.xml --spaces 2 ``` ```bash # JSON to XML xml-js input.json --spaces 2 --out output.xml ``` ```bash # With custom formatting xml-js data.xml --compact --trim --native-type ``` -------------------------------- ### Always Create Elements Array (Non-Compact Format) Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Ensures that in non-compact format, an `elements` array is always created, even for leaf elements. ```bash xml-js input.xml --always-children ``` -------------------------------- ### JSON to Pretty XML Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Converts a JSON file (expected in compact format) to formatted XML and saves it to a specified output file. The --compact flag indicates the input JSON is compact. ```bash xml-js data.json --spaces 2 --compact --out result.xml # Note: --compact indicates input is compact format ``` -------------------------------- ### Element Writing Flow (Compact) Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/architecture.md Details the process for writing XML elements in a compact format, iterating through object keys and handling special properties like _text and _attributes. ```text Object ↓ writeElementsCompact(element, options, depth) ├─ Iterate over keys ├─ For each key: │ ├─ Check for special keys (_text, _attributes, etc.) │ ├─ Skip parent and attributes keys │ ├─ For element keys: writeElementCompact() │ │ └─ Recursively handle nested elements │ └─ For special properties: apply specific writers └─ Return XML XML string ``` -------------------------------- ### Read/Write XML and JSON Files Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/usage-patterns.md Use these functions to convert XML files to JSON and vice-versa, saving the output to specified file paths. Ensure the 'fs' and 'xml-js' modules are imported. ```javascript const convert = require('xml-js'); const fs = require('fs'); // XML file → JSON file function xmlToJsonFile(inputPath, outputPath, options = {}) { const xml = fs.readFileSync(inputPath, 'utf8'); const json = convert.xml2json(xml, { compact: true, spaces: 2, ...options }); fs.writeFileSync(outputPath, json, 'utf8'); } // JSON file → XML file function jsonToXmlFile(inputPath, outputPath, options = {}) { const json = fs.readFileSync(inputPath, 'utf8'); const xml = convert.json2xml(json, { compact: true, spaces: 2, ...options }); fs.writeFileSync(outputPath, xml, 'utf8'); } // Usage xmlToJsonFile('input.xml', 'output.json'); jsonToXmlFile('config.json', 'config.xml'); ``` -------------------------------- ### Assume XML Input and Output JSON Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md If the input file has an extension other than `.xml` or `.json`, `xml-js` assumes it is XML and converts it to JSON. ```bash xml-js data.txt ``` -------------------------------- ### Customize Elements Key Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Changes the key used for non-compact format child elements. The default is `elements`. ```bash xml-js input.xml --elements-key ``` -------------------------------- ### Convert JSON to XML and Save to File Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Use the `--out` option to save the converted XML to a specified file when the input is a JSON file. ```bash xml-js data.json --out data.xml ``` -------------------------------- ### Enable Compact JSON Format Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Use this option for JSON input where element names are keys, differing from the non-compact format with explicit type properties. ```bash xml-js input.xml --compact ``` -------------------------------- ### Combining Multiple XML to JSON Options Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/api-reference-xml2json.md Demonstrates combining multiple options like 'compact', 'trim', and 'nativeType' for advanced XML to JSON conversion. 'nativeType' converts values to their native types (e.g., numbers, booleans). ```javascript const convert = require('xml-js'); const xml = "\n \n Widget\n Gadget\n \n"; const result = convert.xml2json(xml, { compact: true, trim: true, nativeType: true, spaces: 2 }); // Result: // { // "items": { // "item": [ // { // "_attributes": { // "id": 1, // "status": "active" // }, // "_text": "Widget" // }, // { // "_attributes": { // "id": 2, // "status": "inactive" // }, // "_text": "Gadget" // } // ] // } // } ``` -------------------------------- ### Customizing XML Declaration Key Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/configuration.md Demonstrates how to change the property name for XML declarations using `declarationKey`. The default is 'declaration' or '_declaration' depending on the compact mode. ```javascript // Default _declaration: { _attributes: { version: '1.0' } } // With declarationKey: '$decl' $decl: { _attributes: { version: '1.0' } } ``` -------------------------------- ### Webpack Configuration for xml-js Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/module-exports.md No special configuration is needed for Webpack. Import the library directly. ```javascript // No special configuration needed import { xml2js } from 'xml-js'; ``` -------------------------------- ### Invoke Callback for Instruction Name Transformation Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/architecture.md Handles name transformations for instructions using a specific callback function if defined in options. ```javascript // For instructions with both name and value transformations if ('instructionNameFn' in options) { // Rename the instruction } ``` -------------------------------- ### Convert XML to JSON (Compact and Non-Compact) Source: https://github.com/nashwaan/xml-js/blob/master/README.md Demonstrates converting an XML string to both compact and non-compact JSON formats using the xml-js library. Ensure the 'xml-js' module is required. ```javascript var convert = require('xml-js'); var xml = '' + '' + ' Happy' + ' Work' + ' Play' + ''; var result1 = convert.xml2json(xml, {compact: true, spaces: 4}); var result2 = convert.xml2json(xml, {compact: false, spaces: 4}); console.log(result1, '\n', result2); ``` -------------------------------- ### Minified JSON Output Configuration Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/configuration.md Use this configuration for a compact JSON output with no extra whitespace. ```javascript { compact: true, spaces: 0 } ``` -------------------------------- ### Convert JSON to XML using CLI Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/README.md Convert a JSON file to XML using the `xml-js` CLI tool. Specify the output file with `--out` and indentation with `--spaces`. ```bash # Convert JSON to XML xml-js input.json --spaces 2 --out output.xml ``` -------------------------------- ### Custom Key Names for Conversion Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Converts XML to JSON using custom key names for text, attributes, and comments. This allows for greater control over the resulting JSON structure. ```bash xml-js input.xml --compact --spaces 2 \ --text-key value \ --attributes-key attrs \ --comment-key note ``` -------------------------------- ### Convert XML to JSON using CLI Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/README.md Use the `xml-js` command-line tool to convert an XML file to JSON, specifying the output indentation with `--spaces`. ```bash # Convert XML to JSON xml-js input.xml --spaces 2 ``` -------------------------------- ### JSON to XML Auto-Detection Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md When the input file has a `.json` extension, `xml-js` automatically converts it to XML. ```bash xml-js data.json ``` -------------------------------- ### Convert JSON with Attributes to XML Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/api-reference-json2xml.md Demonstrates how to include XML attributes in the converted XML by using the `_attributes` key in the JSON object. ```javascript const convert = require('xml-js'); const json = { book: { _attributes: { id: '123', author: 'John' }, title: { _text: 'XML Guide' } } }; const xml = convert.json2xml(json, { compact: true }); // Result: XML Guide ``` -------------------------------- ### Customize Name Key Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Changes the key used for non-compact format element names. The default is `name`. ```bash xml-js input.xml --name-key ``` -------------------------------- ### Customize Declaration Key Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Changes the key used for XML declarations. The default is `declaration` (non-compact) or `_declaration` (compact). ```bash xml-js input.xml --declaration-key ``` -------------------------------- ### JSON to XML Conversion Pipeline Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/README.md Illustrates two approaches for converting JSON to XML strings: using json2xml directly or parsing JSON to a JS object and then using js2xml. ```text JSON string ──json2xml()──> XML string (or) JSON string ──JSON.parse()──> JS object ──js2xml()──> XML string ``` -------------------------------- ### JSON to XML and Back to JSON Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/module-exports.md Shows the process of converting a JSON string to XML using `json2xml` and then parsing the resulting XML back into a JSON string with `xml2json`. Useful for data interchange formats. ```javascript const convert = require('xml-js'); // Convert JSON to XML const xml = convert.json2xml(jsonString); // Parse XML back to JSON const json = convert.xml2json(xml); // Original and final JSON should be equivalent ``` -------------------------------- ### Customize Instruction Key Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Changes the key used for processing instructions. The default is `instruction` (non-compact) or `_instruction` (compact). ```bash xml-js input.xml --instruction-key ``` -------------------------------- ### Convert XML to JSON and vice versa Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/README.md Use `xml2json` for XML to JSON conversion and `json2xml` for the reverse. Options like `compact` and `spaces` control the output format. ```javascript const json = convert.xml2json(xml, { compact: true, spaces: 2 }); const xml = convert.json2xml(json, { compact: true, spaces: 2 }); ``` -------------------------------- ### XML to JSON String and Back Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/module-exports.md Illustrates parsing an XML string into a JSON string using `xml2json` and then converting that JSON string back into XML using `json2xml`. Suitable for scenarios where JSON string representation is preferred. ```javascript const convert = require('xml-js'); // Parse XML to JSON string const json = convert.xml2json(xmlString); // Convert JSON back to XML const xml = convert.json2xml(json); ``` -------------------------------- ### Type-safe XML Conversions with xml-js Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/README.md Demonstrates type-safe conversions using xml2js with explicit return types for both compact and non-compact modes. Ensure correct types are imported for Element and ElementCompact. ```typescript // Type-safe conversions import { xml2js, Element, ElementCompact } from 'xml-js'; // Use explicit return type const result: Element = xml2js(xml, { compact: false }); const compact: ElementCompact = xml2js(xml, { compact: true }); ``` -------------------------------- ### Write Options (js2xml, json2xml) Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/quick-reference.md Options available for writing JavaScript/JSON to XML. ```APIDOC ## Write Options ### Options | Option | Type | Default | Purpose | |--------|------|---------|---------| | compact | boolean | false | Input format: true for compact, false for non-compact | | spaces | number | string | 0 | Indentation: number of spaces or string like '\t' | | fullTagEmptyElement | boolean | false | Use `` instead of `` for empty elements | ``` -------------------------------- ### Browser Usage with Bundler Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/README.md Import and use xml-js functions like xml2json and json2xml in browser environments when using a module bundler. ```javascript import { xml2json, json2xml } from 'xml-js'; const json = xml2json(xmlString, { compact: true }); const xml = json2xml(json, { compact: true }); ``` -------------------------------- ### XML to JSON Auto-Detection Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md When the input file has a `.xml` extension, `xml-js` automatically converts it to JSON. ```bash xml-js data.xml ``` -------------------------------- ### Generate XML Programmatically Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/quick-reference.md Construct a JavaScript object representing the desired XML structure and use `js2xml` with `compact: true` and `spaces: 2` to convert it to XML. ```javascript const obj = { root: { _attributes: { version: '1.0' }, child: { _text: 'content' } } }; convert.js2xml(obj, { compact: true, spaces: 2 }) ``` -------------------------------- ### Customize Text Key Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Changes the key used for element text content. The default is `text` (non-compact) or `_text` (compact). ```bash xml-js input.xml --text-key ``` ```bash xml-js input.xml --text-key value # Instead of _text: 'content', uses value: 'content' ``` -------------------------------- ### Convert XML to JSON via CLI Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/quick-reference.md Use the `xml-js` command-line tool to convert an XML file to JSON, with options for pretty-printing. ```bash # XML to JSON xml-js file.xml --spaces 2 ``` -------------------------------- ### XML to JavaScript Object and Back Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/module-exports.md Demonstrates the conversion flow from an XML string to a JavaScript object using `xml2js` and then back to an XML string using `js2xml`. Useful for parsing and manipulating XML data in memory. ```javascript const convert = require('xml-js'); // Parse XML to object const obj = convert.xml2js(xmlString); // Convert back to XML const xml = convert.js2xml(obj); // Original and final XML should be equivalent ``` -------------------------------- ### Writing Options Flow Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/architecture.md Details the process of converting a JavaScript object to an XML string. It covers option validation, choosing the appropriate writing function (compact or non-compact), applying formatting and callbacks, and character escaping. ```text JS Object ↓ js2xml(obj, userOptions) ├─ validateOptions(userOptions) │ └─ Convert number spaces to string ├─ writeElementsCompact() or writeElements() │ └─ Based on compact option ├─ For each element: │ ├─ Apply ignore options (ignoreText, ignoreComment, etc.) │ ├─ Apply formatting options (spaces, indentation, fullTag, etc.) │ ├─ Apply callback functions (textFn, elementNameFn, etc.) │ └─ Escape special characters (&, <, >, ") └─ Return formatted XML string ``` -------------------------------- ### Use Full Tag for Empty Elements Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Enables writing empty XML elements as instead of the shorthand . ```bash xml-js input.xml --full-tag ``` -------------------------------- ### Set Indentation Spaces Source: https://github.com/nashwaan/xml-js/blob/master/_autodocs/command-line.md Specify the number of spaces for indentation. Defaults to 0 for minified output. ```bash xml-js input.xml --spaces ``` ```bash # 2-space indentation xml-js input.xml --spaces 2 ``` ```bash # 4-space indentation xml-js input.json --spaces 4 ``` ```bash # No indentation (minified) xml-js input.xml ```