Leonidas-from-XIV / node-xml2js

XML to JavaScript object converter.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

emptyTag doesn't behave as expected.

iSued opened this issue · comments

this is said in the docs:
emptyTag (default: ''): what will the value of empty nodes be. In case you want to use an empty object as a default value, it is better to provide a factory function () => ({}) instead. Without this function a plain object would become a shared reference across all occurrences with unwanted behavior.

      emptyTag: () => new Array(1, 2, 2, 2, 2),
      explicitRoot: true,
      explicitArray: false,
      mergeAttrs: true,
      preserveChildrenOrder: true,
      attrValueProcessors: [customParser],
      validator: () => {},
      includeWhiteChars: true,
    })

The code above or any other function with a return of object, makes my converted tags disappear from the final JSON.
My node version is Node.js v16.15.0.

The problem was typescript and i solved by ignoring it.

    const parser = new xml2js.Parser({
      //!!!! WARNING Non cancellare il ts-ignore qui sotto!!!!
      // @ts-ignore: Unreachable code error
      emptyTag: _emptyTag(),
      explicitRoot: false,
      explicitArray: false,
      mergeAttrs: true,
      preserveChildrenOrder: true,
      attrValueProcessors: [customParser],
      includeWhiteChars: true,
    })

where:

function _emptyTag() {
  return new Array()
}

The problem was caused by the fact that in the exporting file of the library:

export interface ParserOptions {
    attrkey?: string | undefined;
    charkey?: string | undefined;
    explicitCharkey?: boolean | undefined;
    trim?: boolean | undefined;
    normalizeTags?: boolean | undefined;
    normalize?: boolean | undefined;
    explicitRoot?: boolean | undefined;
    emptyTag?: (() => any) | string 
    explicitArray?: boolean | undefined;
    ignoreAttrs?: boolean | undefined;
    mergeAttrs?: boolean | undefined;
    validator?: Function | undefined;
    xmlns?: boolean | undefined;
    explicitChildren?: boolean | undefined;
    childkey?: string | undefined;
    preserveChildrenOrder?: boolean | undefined;
    charsAsChildren?: boolean | undefined;
    includeWhiteChars?: boolean | undefined;
    async?: boolean | undefined;
    strict?: boolean | undefined;
    attrNameProcessors?: Array<(name: string) => any> | undefined;
    attrValueProcessors?: Array<(value: string, name: string) => any> | undefined;
    tagNameProcessors?: Array<(name: string) => any> | undefined;
    valueProcessors?: Array<(value: string, name: string) => any> | undefined;
    chunkSize?: number | undefined;
}

emptyTag is typed in this way:

    emptyTag?: (() => any) | string 

but when using the function without calling it with parentheses it doesn't work as the library is not processing it. so the type ()=>any seems to be wrong.