53

Is there a good way to create XML files? For example, like the Builder for Rails (or any other way)?

Thanks

3 Answers 3

73

It looks like the xmlbuilder-js library may do this for you. If you have npm installed, you can npm install xmlbuilder.

It will let you do this (taken from their example):

var builder = require('xmlbuilder');
var doc = builder.create('root');

doc.ele('xmlbuilder')
    .att('for', 'node-js')
    .ele('repo')
      .att('type', 'git')
      .txt('git://github.com/oozcitak/xmlbuilder-js.git') 
    .up()
  .up()
  .ele('test')
    .txt('complete');

console.log(doc.toString({ pretty: true }));

which will result in:

<root>
  <xmlbuilder for="node-js">
    <repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>
  </xmlbuilder>
  <test>complete</test>
</root>
Sign up to request clarification or add additional context in comments.

5 Comments

I'm having a small issue with this. I posted on github if you're interested in lending a hand.
Thanks for the answer, here i found a tutorial on this topic, I hope it will be helpful for someone. programmerblog.net/generate-xml-with-nodejs-and-mysql
Can I write the result on a .xml file?
@BiruelRick, it will give you a string formattd as xml. You can use fs module to write to a file. Hope this helps
The api has changed a bit, the latest documentation is available here
5

recent changes to xmlbuilder require root element name passed to create()

see working example

var builder = require('xmlbuilder');
var doc = builder.create('root')
  .ele('xmlbuilder')
    .att('for', 'node-js')
    .ele('repo')
      .att('type', 'git')
      .txt('git://github.com/oozcitak/xmlbuilder-js.git') 
      .up()
    .up()
  .ele('test')
  .txt('complete')
.end({ pretty: true });
console.log(doc.toString());

Comments

4

xmlbuilder was discontinued and replaced by xmlbuilder2, which has been redesigned from the ground up to be fully conforming to the modern DOM specification.

To install xmlbuilder2 using npm:

npm install xmlbuilder2

An example, from their home page, for creating a new XML file with it:

const { create } = require('xmlbuilder2');

const root = create({ version: '1.0' })
  .ele('root', { att: 'val' })
    .ele('foo')
      .ele('bar').txt('foobar').up()
    .up()
    .ele('baz').up()
  .up();

// convert the XML tree to string
const xml = root.end({ prettyPrint: true });
console.log(xml);

Will result in:

<?xml version="1.0"?>
<root att="val">
  <foo>
    <bar>foobar</bar>
  </foo>
  <baz/>
</root>

Comments

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.