0

I am using fast-xml-parser and have a challenge in preserving leading zeros. I have simplified the example to the core of my problem.

I would like to preserve these leading zeros in the value of an item in the xmlOutput. I want xmlOutput to eventually equal xmlInput, so xmlOutput should be

 <item>08</item> instead of <item>8</item> which is what I get now.

How can I configure that?

Run the code beneath as follows: node xmlparse

const { XMLParser, XMLBuilder, XMLValidator } = require("fast-xml-parser");

const options = {
    parseTrueNumberOnly: true  //if true then values like "+123", or "0123" will not be parsed as number.
};

const xmlInput = '<item>08</item>';
console.log(xmlInput);  

const parser = new XMLParser(options);
let jsonData = parser.parse(xmlInput);
console.log(JSON.stringify(jsonData));

const builder = new XMLBuilder();
const xmlOutput = builder.build(jsonData,options)
console.log(xmlOutput);

I expected <item>08</item> but I got <item>8</item>

2 Answers2

1
const options = 
      {
        "alwaysCreateTextNode": false,
        "attributeNamePrefix": "@_",
        "attributesGroupName": false,
        "textNodeName": "#text",
        "ignoreAttributes": true,
        "removeNSPrefix": true,
        "parseNodeValue": true,
        "parseAttributeValue": false,
        "allowBooleanAttributes": false,
        "trimValues": true,
        "cdataTagName": "#cdata",
        "preserveOrder": false,
        "numberParseOptions": {
            "hex": false,
            "leadingZeros": false
        }
    }
  
    //OPTION
   
    const parser = new XMLParser(options);
    let jObj = parser.parse(data);
BACKCODE
  • 11
  • 1
0
const options = {
  parseTrueNumberOnly : true,
};

let xml = `<root><value>0123</value></root>`;
let res = fastXmlParser.parse(xml, options);
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jul 15 '23 at 09:02