Leonidas-from-XIV / node-xml2js

XML to JavaScript object converter.
MIT License
4.87k stars 601 forks source link

How to get child text in parent charkey ? #557

Open henricazottes opened 4 years ago

henricazottes commented 4 years ago

I have the following example:

const parser = new xml2js.Parser({
    explicitArray: false,
});

parser.parseStringPromise(
    `<sentence>This library is <adjective>awesome</adjective>!</sentence>
`).then(console.log)    

Which results to:

XML: {
  "sentence": {
    "_": "This library is !",
    "adjective": "awesome"
  }
}

You can see that the child tag adjective text is striped away in the charkey. But the problem is that there is no way to find where the awesome word originally was placed, making impossible to reconstruct the sentence by hand.

I would love to have a text key somewhere which would return the whole text This library is awesome!. Is that possible ?

Omega-Ariston commented 4 years ago

You can try overload the ontext()method, for example"

    const parser = new xml2js.Parser({ explicitArray: false });

    const ontextFun = parser.saxParser.ontext;

    parser.saxParser.ontext = function (text) {
        console.log(text);
        ontextFun(text);
    }

    parser.parseStringPromise(`<sentence>This library is <adjective>awesome</adjective>!</sentence>`).then(console.log);

The output of parser.saxParser.ontext

This library is 
awesome
!
JohnTendik commented 4 years ago

Im actually in need of doing this as well, none of the function parsers were able to help me achieve this. The example above by @Omega-Ariston did not work for a full xml document..

Does anyone have any ideas on how to do this?