Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: How to create XML files

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

Thanks

like image 739
donald Avatar asked Sep 02 '11 15:09

donald


People also ask

How do you write data in XML using node JS?

var obj = {title: "Tony", link: "Stark" , "description":"hi"}; var fs = require('fs'); var xml2js = require('xml2js'); var builder = new xml2js. Builder(); var xml = builder. buildObject(obj); fs. writeFile('feed.


2 Answers

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> 
like image 147
Dylan Markow Avatar answered Oct 04 '22 07:10

Dylan Markow


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()); 
like image 23
user3218782 Avatar answered Oct 04 '22 05:10

user3218782