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.53k stars 303 forks source link

How to handle values as string #597

Closed waghcwb closed 1 year ago

waghcwb commented 1 year ago

Description

I want to know how to parse values as strings, because the parse is changing data in my XML

Code

async function Main() {
  let parser = new XMLParser()
  let object = parser.parse(`
    <?xml version="1.0"?>
    <any_name>
        <person>
            <phone>600.00</phone>
        </person>
    </any_name>
  `)
  console.info(object)
  // { '?xml': '', any_name: { person: { phone: 600 } } }
}

Output

{ '?xml': '', any_name: { person: { phone: 600 } } }

expected data

{ '?xml': '', any_name: { person: { phone: '600.00' } } }

Would you like to work on this issue?

github-actions[bot] commented 1 year 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 1 year ago

Please check strnum option and library for appropriate configuration.

cecia234 commented 1 year ago

Hi, you can set parseTagValue: false inside the options to avoid having strnum parse the value for you.

let options =  {
    parseTagValue: false,
}
let parser = new XMLParser(options)
let object = parser.parse(`
    <?xml version="1.0"?>
    <any_name>
        <person>
            <phone>600.00</phone>
        </person>
    </any_name>
`)
console.info(object)
// { '?xml': '', any_name: { person: { phone: '600.00' } } }

You can also specify a custom tag parser inside the options object (tagValueProcessor property) to handle different cases based on your needs:

let options =  {
    parseTagValue: false,
    tagValueProcessor: (tagName, tagValue) => {
        if (typeof tagValue === 'string') {
            return "HELLO!";
        } else if (tagValue === undefined || tagValue === null) {
            return null;
        }
        return tagValue.toString();
    }
}
let parser = new XMLParser(options)
let object = parser.parse(`
    <?xml version="1.0"?>
    <any_name>
        <person>
            <phone>600.00</phone>
        </person>
    </any_name>
  `)
console.info(object)
// { '?xml': '', any_name: { person: { phone: "HELLO!" } } }
amitguptagwl commented 1 year ago

I hope the issue is not anymore, or you can start the discussion thread.