Leonidas-from-XIV / node-xml2js

XML to JavaScript object converter.
MIT License
4.88k stars 602 forks source link

Builder add prefix #500

Open ataft opened 5 years ago

ataft commented 5 years ago

When going from XML to JS, the "processors.stripPrefix" allows you to remove the prefix. Is it possible for the Builder to have an option for addPrefix?

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

results in:

<v10:foo>
  <v10:bar>
    <v10:hello>world</v10:hello>
  </v10:bar>
</v10:foo>
JoseAnt86 commented 4 years ago

Any solution to this problem ?? help please

johel commented 3 years ago

I've created this function in order to set a prefix to all keys in a given object:

function isRealObject(obj) {
  return typeof obj === 'object' && obj !== null;
}

function addPrefixToKeys(obj, prefix) {
  return Object.fromEntries(
    Object.entries(obj).map(([k, v]) => {
      const prefixedValue = isRealObject(v) ? addPrefixToKeys(v, prefix) : v;
      return [prefix + k, prefixedValue];
    })
  );
}

But maybe there is something native on the lib, I just couldn't find it.