1

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 Answer 1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

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.
No problem. You could accept my answer as the solution then, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.