xml-js

repository·master·Indexed 23 days ago

https://github.com/nashwaan/xml-js

A utility library for converting between XML text and JavaScript objects or JSON text. It supports both 'compact' mode for concise structures and 'non-compact' mode for preserving element order and full reversibility. The library provides methods such as xml2json, xml2js, js2xml, and json2xml, with extensive configuration options for handling attributes, CData, comments, and custom processing via callback functions.

Tokens
4.9K
Snippets
8
Records
23
Agent score
79%

What's inside xml-js

  1. Understand Compact vs Non-Compact modes

    master

    xml-js supports two modes for representing XML in JSON/JavaScript objects:

    Compact Mode ({compact: true})

    • Pros: Concise and saves space.
    • Cons: Can lose the original order of elements if elements with the same name are mixed with other elements. For example, <a/><b/><a/> might be merged into {a:[{},{}], b:{}}, losing the sequence a -> b -> a.
    • Use case: When space is a priority and element order/reversibility is not critical.

    Non-Compact Mode ({compact: false})

    • Pros: Guarantees the preservation of element order and is fully reversible. It uses an elements array to store nodes, ensuring that even if multiple nodes have the same name, their sequence is maintained.
    • Cons: More verbose and consumes more memory/space.
    • Use case: When you need to convert the JSON back to the exact original XML or when element order matters.

    Tip: You can reduce the output size of non-compact mode by using shorter key names via configuration options.

  2. Use xml-js as a local script in package.json

    master

    To use xml-js as part of your project's automation (e.g., via npm scripts) without installing it globally:

    1. Install it locally:
    npm install --save xml-js
    1. Add a script to your package.json:
    {
      "dependencies": {
        "xml-js": "latest"
      },
      "scripts": {
        "convert": "xml-js test.json --spaces 4"
      }
    }
    1. Run the script:
    npm run convert
  3. Use xml-js via Command Line Interface

    master

    The xml-js library can be used directly from the terminal. The conversion type (XML $\leftrightarrow$ JSON) is automatically inferred from the file extension of the source file.

    Global Installation

    Install globally to use xml-js anywhere:

    npm install -g xml-js

    Usage Examples

    Convert JSON to XML and print to screen:

    xml-js test.json --spaces 4

    Convert JSON to XML and save to file:

    xml-js test.json --spaces 4 --out test.xml

    Convert XML to JSON and print to screen:

    xml-js test.xml --spaces 4

    Convert XML to JSON and save to file:

    xml-js test.xml --spaces 4 --out test.json
    npm install -g xml-js
    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
  4. Optimize key names for compact and non-compact modes

    master

    Compact Mode Optimization

    In compact mode, you can reduce the size of your output by using single-character keys:

    { textKey: '_', attributesKey: '$', commentKey: 'value' }

    Non-Compact Mode Consistency

    In non-compact mode, you can make it easier for client code to traverse contents by setting textKey, cdataKey, and commentKey to the same value:

    { textKey: 'value', cdataKey: 'value', commentKey: 'value' }
  5. Quick start with xml-js

    master

    To quickly convert XML to both compact and non-compact JSON formats, import xml-js and use the xml2json method.

    Note that compact: true produces a more concise JSON structure, while compact: false produces a more verbose structure that preserves the exact order of elements and is fully reversible.

    var convert = require('xml-js');
    var xml =
    '<?xml version="1.0" encoding="utf-8"?>' +
    '<note importance="high" logged="true">' +
    '    <title>Happy</title>' +
    '    <todo>Work</todo>' +
    '    <todo>Play</todo>' +
    '</note>';
    var result1 = convert.xml2json(xml, {compact: true, spaces: 4});
    var result2 = convert.xml2json(xml, {compact: false, spaces: 4});
    console.log(result1, '\n', result2);
  6. Install xml-js

    master

    You can install xml-js as a project dependency using npm, or install it globally to use it as a command-line converter.

    To install as a dependency:

    npm install --save xml-js

    To install globally:

    npm install --global xml-js
  7. Use the xml-js CLI for conversions

    master

    The xml-js CLI allows you to convert between XML and JSON formats directly from your terminal. It automatically detects the conversion direction based on the file extension of the source file: .xml files are converted to JSON, and .json files are converted to XML.

    Basic Usage

    Convert XML to JSON:

    xml-js src.xml

    Convert JSON to XML:

    xml-js src.json

    Save output to a file: Use the --out flag to specify the destination file.

    xml-js src.xml --out output.json

    Pipe input via stdin: You can pipe XML content into the CLI, and it will output the JSON result to stdout.

    cat file.xml | xml-js
  8. Convert XML to JavaScript object or JSON text

    master

    Use xml2js() to convert XML text into a JavaScript object, or xml2json() to convert XML text into a JSON string. Both functions accept an optional options object to control the conversion behavior.

    var convert = require('xml-js');
    var xml = require('fs').readFileSync('test.xml', 'utf8');
    var options = {ignoreComment: true, alwaysChildren: true};
    var result = convert.xml2js(xml, options); // or convert.xml2json(xml, options)
    console.log(result);
  9. Customize XML to JSON conversion with callback functions

    master

    When converting XML to a JS object or JSON using xml2json, you can provide custom callback functions in the options object to process specific parts of the XML structure (like element names, attributes, or text) during the conversion process.

    Example of using elementNameFn to transform element names:

    var convert = require('xml-js');
    var xml = '<foo:Name>Ali</Name> <bar:Age>30</bar:Age>';
    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"}}
  10. Customize JSON to XML conversion with callback functions

    master

    When converting a JS object or JSON to XML using json2xml, you can provide custom callback functions in the options object to control how elements, attributes, and text are generated.

    Example of using textFn to conditionally modify text content:

    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); // <foo:Name>Ali</Name> <bar:Age>30</bar:Age>
  11. Convert JS object or JSON to XML

    master

    Use js2xml() to convert a JavaScript object to XML text, or json2xml() to convert a JSON string to XML text.

    var convert = require('xml-js');
    var json = require('fs').readFileSync('test.json', 'utf8');
    var options = {compact: true, ignoreComment: true, spaces: 4};
    var result = convert.json2xml(json, options);
    console.log(result);
  12. Reference: xml-js CLI arguments

    master

    The xml-js CLI accepts a source file and several options to control the conversion behavior.

    Usage: xml-js src [options]

    Arguments:

    • src: Input file (conversion type inferred from extension).

    Options:

    • --help, -h: Display help.
    • --version, -v: Display version.
    • --out: Output file path.
    • --spaces: Indentation amount.
    • --full-tag: Always use `<a

    </a>` form for XML elements.

    • --no-decl: Ignore <?xml?> declaration.
    • --no-inst: Ignore processing instructions <?...?>.
    • --no-attr: Ignore attributes.
    • --no-text: Ignore element texts.
    • --no-cdata: Ignore CData.
    • --no-doctype: Ignore DOCTYPE.
    • --no-comment: Ignore comments.
    • --trim: Trim whitespace surrounding texts.
    • --compact: Use compact JSON form.
    • --native-type: Coerce numbers and booleans to native types.
    • --always-array: Every element is always an array (requires --compact).
    • --always-children: Every element always contains sub-elements (requires non-compact).
    • --text-key: Change default 'text' key.
    • --cdata-key: Change default 'cdata' key.
    • --doctype-key: Change default 'doctype' key.
    • --comment-key: Change default 'comment' key.
    • --attributes-key: Change default 'attributes' key.
    • --declaration-key: Change default 'declaration' key.
    • --instruction-key: Change default 'processing instruction' key.
    • --type-key: Change default 'type' key (non-compact only).
    • --name-key: Change default 'name' key (non-compact only).
    • --elements-key: Change default 'elements' key (non-compact only).