nodejs xml作成パッケージxmlbuilder2

nodejsでxmlを作成することができる。

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);

チェインして構築することも出来るし、

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

const obj = {
 root: {
   '@att': 'val',
   foo: {
     bar: 'foobar'
   },
   baz: {}
 }
};

const doc = create(obj);
const xml = doc.end({ prettyPrint: true });
console.log(xml);

配列でぶちこむこともできる。

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

const xmlStr = '<root att="val"><foo><bar>foobar</bar></foo></root>';
const doc = create(xmlStr);

// append a 'baz' element to the root node of the document
doc.root().ele('baz');

const xml = doc.end({ prettyPrint: true });
console.log(xml);

また、テンプレート的に外枠を作っておいて、そこに追加していくこともできる。かなり便利だと思う。

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

const root = create().ele('squares');
root.com('f(x) = x^2');
for(let i = 1; i <= 5; i++)
{
 const item = root.ele('data');
 item.att('x', i);
 item.att('y', i * i);
}

const xml = root.end({ prettyPrint: true });
console.log(xml);

オブジェクトを取得してその内容を変更することもできる。便利。

この記事が気に入ったらサポートをしてみませんか?