Open sandgupta23 opened 6 years ago
please refer this issue for more information https://github.com/nashwaan/xml-js/issues/58
I saw the code and you should add compact to options if you want a compact conversion otherwise you should add elementskey. I think that the lib should have compact True by default, so that if you don't put options It works. Otherwise It should have a better documentation
@sangupta007
As highlighted by @euberdeveloper, the library assumes the input is in non-compact form unless you explicitly pass compact: true
option to indicate the input is in compact form.
So, to fix your example, use this code:
var convert = require('xml-js');
console.log(convert.json2xml(JSON.stringify({"name":'john'}), {compact: true}));
// console.log(convert.js2xml(JSON.stringify({"name":'john'}), {compact: true})); // won't work, read below
console.log(convert.json2xml({"name":'john'}, {compact: true}));
console.log(convert.js2xml({"name":'john'}, {compact: true}));
The second case will not work because you are passing JSON object to convert.js2mxl()
.
@euberdeveloper I admit the documentation doesn't tell or warn the library works in non-compact form by default. I got tripped into this issue many times myself 😅.
Changing the default behavior to compact form might cause breaking change to existing codes. So I don't think I will go this track.
I will update the documentation to clarify this default. I might also let the library automatically switch the behavior to compact form if the input is in compact form.
Thanks for reminding me to set compact
to true
everywhere.
Can't the default be set to true? As most json/js objects are of compact form?
I think that if it was done, the module would loose retro-compatibility support. If it was done, the first of the three version-numbers should be incremented
var convert = require('xml-js');
console.log(convert.json2xml(JSON.stringify({"name":'john'}))); console.log(convert.js2xml(JSON.stringify({"name":'john'}))); console.log(convert.json2xml({"name":'john'})); console.log(convert.js2xml({"name":'john'}));
all are printing ""