node-xml2js
node-xml2js copied to clipboard
How to get child text in parent charkey ?
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 ?
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
!
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?