nashwaan / xml-js

Converter utility between XML text and Javascript object / JSON text.
MIT License
1.27k stars 180 forks source link

json to xml: Auto convert < to &lt #209

Open anhuet opened 11 months ago

anhuet commented 11 months ago

I'm using json2xml

var convert = require('xml-js');
var json = require('fs').readFileSync('test.json', 'utf8');
var options = {compact: true, ignoreComment: true, spaces: 4};
var result = convert.json2xml(json, options);
console.log(result);

Here is test.json file

{
    "value": [
        {
            "_text": "\"test < \""
        }
    ]
}

Result: <value>"test &lt; "</value>

Expect: <value>"test < "</value>

Is there any way to ignore auto convert < to &lt

liuyib commented 3 months ago

@anhuet

The sanitize options can ignore this behavior, but it has been deprecated.

The follow code can help you:

const res = convert.json2xml(
    JSON.stringify({
      value: [
        {
          _text: '"test < "',
        },
      ],
    }),
    {
      compact: true,
      textFn: (value) => {
        return value.replace("&lt;", "<");
      },
    }
  );

  // <value>"test < "</value>
  console.log(res);