NaturalIntelligence / fast-xml-parser

Validate XML, Parse XML and Build XML rapidly without C/C++ based libraries and no callback.
https://naturalintelligence.github.io/fast-xml-parser/
MIT License
2.43k stars 297 forks source link

Configuration to explicitly disable number parsing for specific xml tag values #661

Closed kule1015 closed 1 week ago

kule1015 commented 3 weeks ago

Description

Hi there,

when parsing an XML tag that can have tag values of "A6" or "6.0", the intention is that the specific XML tag values are always handled as strings. An attempt was made to utilise the parser option "tagValueProcessor". During debugging, it was observed that within the function OrderedObjParser.parseTextData, the function OrderedObjParser.parseValue is called on the result of the callback of tagValueProcessor. The function OrderedObjParser.parseValue will parse the value "6.0" as the integer "6". However, all tag values of "evil" should be parsed as strings.

Did I miss anything or is this intended behavior? Thanks in advance for taking the time!

Input

<evil>6.0</evil>

<evil>A6</evil>

Code

import { XMLParser } from "fast-xml-parser";

const XML_PARSER_OPTIONS = {
  tagValueProcessor: (tagName: string, tagValue: string, jPath: string, hasAttributes: boolean, isLeafNode: boolean) => {
    if (tagName === "evil") {
      return String(tagValue)
    }
    return tagValue;
  },
};

const xmlParser = new XMLParser(XML_PARSER_OPTIONS);

const xml = "<evil>6.0</evil>"

const xml2 = "<evil>A6</evil>"

const parsedXml = xmlParser.parse(xml);
console.log(JSON.stringify(parsedXml))

const parsedXml2 = xmlParser.parse(xml2);
console.log(JSON.stringify(parsedXml2))

Output

{"evil":6}
{"evil":"A6"}

expected data

{"evil":"6.0"}
{"evil":"A6"}

Would you like to work on this issue?

Bookmark this repository for further updates. Visit SoloThought to know about recent features.

github-actions[bot] commented 3 weeks ago

We're glad you find this project helpful. We'll try to address this issue ASAP. You can vist https://solothought.com to know recent features. Don't forget to star this repo.

amitguptagwl commented 2 weeks ago

In your case, you want o set the original value without parsing. As per docs, "If tagValueProcessor returns undefined or null then original value would be set without parsing."

Please check docs for more ways of achieving it. Please also give a try to v5. Let me know if you still need any help.

kule1015 commented 1 week ago

Ah my mistake. Thanks a lot!