loss of leading zeros when using fast-xml-parser

861 views Asked by At

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>

3

There are 3 answers

1
Paul Avijit On
const options = {
  parseTrueNumberOnly : true,
};

let xml = `<root><value>0123</value></root>`;
let res = fastXmlParser.parse(xml, options);
1
kiran On
const { XMLParser } = require('fast-xml-parser');
let data = `<Item>008</Item>`
const options = {
"numberParseOptions": {
    leadingZeros: false
}
};
const parser = new XMLParser(options);
const jObj = parser.parse(data);
console.log(JSON.stringify(jObj));
1
BACKCODE On
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);