5

I am generating xml in nodejs by using xmlbulilder package, now my requirement is to add namespace to xml. for example

<nsA:root xmlns:nsA="namespaceA" xmlns:nsB="namespaceB">
    <nsB:nodeA attrC="valC">nodeText</nsB:nodeA>
</nsA:root>

how we can do it? Thanks for help!

Sachin
  • 109
  • 1
  • 8

1 Answers1

6

I found that you can accomplish it through code like below.

(() => {
    'use strict';

    const xmlbuilder = require('xmlbuilder');

    const doc = xmlbuilder.create('nsA:root')
      .att('xmlns:nsA', 'namespaceA')
      .att('xmlns:nsB', 'namespaceB')
      .ele('nsB:nodeA', 'nodeText')
        .att('attrC', 'valC');

    const output = doc.end({pretty: true});

    console.log(output);
})();

I don't know if there is a more explicit way of setting namespace, but it would make sense to have one to reduce redundancy.

Dmytro
  • 5,068
  • 4
  • 39
  • 50