0

When going from XML to JS, the "processors.stripPrefix" allows you to remove the prefix. Is there any option to add prefix ?

const jsonObj = {
  foo: {
    bar: {
  hello: 'world'
    }
  }
};
const builder = new xml2js.Builder();
const xml = builder.buildObject(jsonObj);
console.log(xml);

//I need this result
<prefix:foo>
  <prefix:bar>
    <prefix:hello>world</prefix:hello>
  </prefix:bar>
</prefix:foo>

Any solution please ??

1 Answers1

1

Based on the official documentation it does not have a feature to add prefixed keys.

You'd have to add them yourself. So this is a workaround that would work for simple objects

const xml2js = require('xml2js')
const jsonObj = {
  foo: {
    bar: {
      hello: 'world'
    }
  }
}
const builder = new xml2js.Builder()
const prefix = 'abc'
const prefixedObj = JSON.parse(
  JSON.stringify(jsonObj)
    .replace(/"([^"]+)":/g, `"${prefix}:$1":`))
const xml = builder.buildObject(prefixedObj)
console.log(xml)

This will produce

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<abc:foo>
  <abc:bar>
    <abc:hello>world</abc:hello>
  </abc:bar>
</abc:foo>
Mestre San
  • 1,806
  • 15
  • 24
  • 1
    Thanks you. Thats the way that i have it and work, but i just wanted to be sure if there is another way to do it using the xml2js lib. Thanks so much for confirming what im doing. – José A Pérez May 15 '20 at 19:37
  • No problem. You could accept my answer as the solution then, right? – Mestre San May 17 '20 at 18:22