js2xmlparser

repository·master·Indexed 42 days ago

https://github.com/michaelkourlas/node-js2xmlparser

A Node.js module for parsing JavaScript objects, arrays, and primitive data types into XML strings. Version 5.0.0 supports advanced constructs including attributes via the '@' property, mixed content via the '#' property, and custom type and wrap handlers through the IOptions interface. It provides functionality to generate complete XML documents with declarations and DTDs using parse(), or inject objects into existing elements using parseToExistingElement().

Tokens
3K
Snippets
9
Records
13
Agent score
53%

What's inside js2xmlparser

  1. How attributes, mixed content, and arrays work in js2xmlparser

    master

    To achieve specific XML structures, use these property patterns within your JavaScript objects:

    Attributes

    To add an attribute to an element, use the @ key. Example: { "@": { type: "home" }, street: "123 St" } becomes <street type="home">123 St</street>.

    Mixed Content (Text Values)

    To add text content to an element that also has attributes, use the # key. Example: { "@": { type: "home" }, "#": "123-555-4567" } becomes <phone type="home">123-555-4567</phone>.

    Multiple Elements

    To create multiple sibling elements with the same name, wrap the objects in an array. Example: phone: [ { "#": "1" }, { "#": "2" } ] becomes <phone>1</phone><phone>2</phone>.

  2. Configure custom wrap handlers for arrays and sets

    master

    The wrapHandlers property in IOptions allows you to customize how arrays and Sets are wrapped in XML.

    • Function Signature: A wrap handler is a function with the signature (key: string, value: unknown) => string | null.
    • Behavior: The function receives the current key and the array/set being processed. It should return a new string to be used as the element name, or null to use the default behavior.
    • Wildcard: You can provide a handler for the key "*" to apply to all arrays/sets, or provide specific keys to target specific array names.
    • Nesting: If the handler returns a new name, the library may create an additional wrapper element depending on the returned value.
  3. Configure custom type handlers in `IOptions`

    master

    The typeHandlers property in IOptions allows you to intercept the conversion process for specific JavaScript types.

    • Type Matching: Handlers are matched using Object.prototype.toString.call(value). For example, an object might be matched by [object Object].
    • Wildcard Handler: You can provide a handler for the key "*" in typeHandlers to act as a catch-all for any type.
    • Suppression: If a handler returns Absent.instance, the corresponding XML element or attribute will be omitted from the output.
  4. Parse JavaScript objects to XML with js2xmlparser.parse()

    master

    Use the parse(rootName, obj) method to convert a JavaScript object into an XML string. The rootName defines the name of the top-level XML element, and obj is the data to be parsed.

    js2xmlparser supports several advanced XML constructs through specific object properties:

    • Attributes: Use the @ property to define attributes for an element.
    • Mixed Content (Text Values): Use the # property to define the text content of an element when that element also contains attributes.
    • Multiple Elements: Use arrays to generate multiple XML elements with the same name.
    • ES2015 Collections: Map objects are treated as JSON-type objects (useful for maintaining element order), and Set objects are treated as arrays.
    • Native Objects: Date and RegExp are handled via their toString methods.
    var js2xmlparser = require("js2xmlparser");
    
    var obj = {
        "@": {
            type: "natural",
        },
        firstName: "John",
        lastName: "Smith",
        dateOfBirth: new Date(1964, 7, 26),
        address: {
            "@": {
                type: "home",
            },
            streetAddress: "3212 22nd St",
            city: "Chicago",
            state: "Illinois",
            zip: 10000,
        },
        phone: [
            {
                "@": {
                    type: "home",
                },
                "#": "123-555-4567",
            },
            {
                "@": {
                    type: "cell",
                },
                "#": "890-555-1234",
            },
            {
                "@": {
                    type: "work",
                },
                "#": "567-555-8901",
            },
        ],
        email: "john@smith.com",
    };
    
    console.log(js2xmlparser.parse("person", obj));
  5. Configure XML Declaration options

    master

    Use IDeclarationOptions to control the <?xml ... ?> declaration at the start of your document.

    • include (boolean): Whether to include the declaration. Default: true.
    • encoding (string): The encoding attribute (e.g., "UTF-8").
    • standalone (string): The standalone attribute. Must be "yes" or "no".
    • version (string): The XML version. Default: "1.0".
    const declaration: IDeclarationOptions = {
        include: true,
        encoding: 'UTF-8',
        standalone: 'yes',
        version: '1.0'
    };
  6. Configure DTD options

    master

    Use IDtdOptions to include a Document Type Definition (DTD) in the generated XML.

    • include (boolean): Whether to include a DTD. Default: false.
    • name (string): The name of the DTD. Required if include is true.
    • sysId (string): The system identifier.
    • pubId (string): The public identifier. If provided, sysId must also be provided.
    const dtd: IDtdOptions = {
        include: true,
        name: 'html',
        pubId: '-//W3C//DTD XHTML 1.0 Strict//EN',
        sysId: 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'
    };
  7. Configure the IOptions interface

    master

    The IOptions interface defines the configuration for parsing an object and formatting the resulting XML. It controls how keys are interpreted as attributes, aliases, or CDATA sections, and how specific data types are handled.

    Key Configuration Options

    • aliasString (string): If a key matches this string, the value associated with that key becomes the name of the XML element. Default: "="".
    • attributeString (string): If a key begins with this string, its value is interpreted as attributes for the parent element. Default: "@".
    • cdataKeys (string[]): Keys matching these strings will have their values enclosed in <![CDATA[...]]> sections. Use "*" to match all keys. Default: [].
    • cdataInvalidChars (boolean): If true, text containing < or & is automatically enclosed in CDATA sections. Default: false.
    • typeHandlers (ITypeHandlers): A map where keys are type strings (from Object.prototype.toString) and values are functions that transform the data. Returning Absent.instance suppresses the value from output.
    • valueString (string): If a key begins with this string, its value is represented as bare text within the element. Default: "#".
    • wrapHandlers (IWrapHandlers): A map used to wrap arrays or sets in specific XML elements. The handler function receives the key and the value (array/set) and returns the element name for each item.
    • useSelfClosingTagIfEmpty (boolean): Enables <element/> instead of <element></element> for empty elements. Default: true.
    • validation (boolean): Enables basic XML validation during construction. Default: true.
    • replaceInvalidChars (boolean): Replaces invalid XML characters with the Unicode replacement character (U+FFFD). Default: false.
    const options: IOptions = {
        aliasString: "=",
        attributeString: "@",
        cdataKeys: ["abc"],
        typeHandlers: {
            "[object Date]": (value) => value.getYear(),
            "[object Null]": (value) => Absent.instance
        },
        wrapHandlers: {
            "abc": (key, value) => "def"
        }
    };
  8. Configure XML formatting options

    master

    Use IFormatOptions to control the visual layout (pretty-printing) of the XML.

    • pretty (boolean): Enables pretty-printing. Default: true (via Options class implementation).
    • indent (string): The string used for indentation. Default: four spaces.
    • newline (string): The newline character. Default: "\n".
    • doubleQuotes (boolean): If true, uses " for attributes; otherwise uses '. Default: false (single quotes).
    const format: IFormatOptions = {
        pretty: true,
        indent: '    ',
        newline: '\n',
        doubleQuotes: false
    };
  9. Add an object to an existing `XmlElement` with `parseToExistingElement()`

    master

    If you are building an XML document manually using xmlcreate and want to inject a JavaScript object into a specific element, use parseToExistingElement.

    Note: This function does not add a root element, an XML declaration, or a DTD. It only parses the object as children of the provided element.

    import { parseToExistingElement } from 'js2xmlparser';
    import { XmlElement } from 'xmlcreate';
    
    const element = new XmlElement({ name: 'root' });
    const obj = { item: 'value' };
    
    parseToExistingElement(element, obj);
    console.log(element.toString());
  10. Convert a JavaScript object to an XML string with `parse()`

    master

    Use the parse function to convert a JavaScript object into a complete XML string. You must provide a root element name; the object's contents will be converted into children of this root element.

    Key features:

    • Supports XML declarations and DTDs via the options object.
    • Handles formatting (indentation/newlines) via options.format.
    • Automatically handles nested objects, arrays, Maps, and Sets.
    import { parse } from 'js2xmlparser';
    
    const obj = { name: 'John', age: 30 };
    const xml = parse('user', obj, { 
      declaration: { include: true },
      format: { indent: '  ' }
    });
    
    console.log(xml);
  11. Reference: IOptions and related interfaces

    master

    The library exports several interfaces for configuring the parsing process. These are primarily used when calling parse() or parseToExistingElement().

    • IOptions: The base configuration interface.
    • IDeclarationOptions: Configuration for the XML declaration.
    • IDtdOptions: Configuration for the Document Type Definition (DTD), including name, pubId, and sysId.
    • IFormatOptions: Configuration for the output string formatting (e.g., indentation).
    • ITypeHandlers: Mapping of type strings to handler functions.
    • IWrapHandlers: Mapping of keys (including "*") to array/set wrapping functions.