package/package.json000644 000766 000024 0000001700 12653252243013020 0ustar00000000 000000 { "name": "xml", "version": "1.0.1", "description": "Fast and simple xml generator. Supports attributes, CDATA, etc. Includes tests and examples.", "homepage": "http://github.com/dylang/node-xml", "keywords": [ "xml", "create", "builder", "json", "simple" ], "author": "Dylan Greene (https://github.com/dylang)", "contributors": [ "Dylan Greene (https://github.com/dylang)", "Dodo (https://github.com/dodo)", "Felix Geisendrfer (felix@debuggable.com)", "Mithgol", "carolineBda (https://github.com/carolineBda)", "Eric Vantillard https://github.com/evantill", "Sean Dwyer https://github.com/reywood" ], "repository": { "type": "git", "url": "http://github.com/dylang/node-xml" }, "bugs": { "url": "http://github.com/dylang/node-xml/issues" }, "devDependencies": { "ava": "^0.11.0" }, "scripts": { "test": "ava" }, "main": "lib/xml.js", "license": "MIT" } package/.npmignore000644 000766 000024 0000000022 12237207722012525 0ustar00000000 000000 node_modules .ideapackage/LICENSE000644 000766 000024 0000002113 12653253767011552 0ustar00000000 000000 (The MIT License) Copyright (c) 2011-2016 Dylan Greene Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package/examples/examples.js000644 000766 000024 0000005301 12237207722014525 0ustar00000000 000000 var xml = require('../lib/xml'); console.log('===== Example 1 ===='); var example1 = { url: 'http://www.google.com/search?aq=f&sourceid=chrome&ie=UTF-8&q=opower' }; console.log(xml(example1)); //http://www.google.com/search?aq=f&sourceid=chrome&ie=UTF-8&q=opower console.log('\n===== Example 2 ===='); var example2 = [ { url: { _attr: { hostname: 'www.google.com', path: '/search?aq=f&sourceid=chrome&ie=UTF-8&q=opower' } } } ]; console.log(xml(example2)); // console.log('\n===== Example 3 ===='); var example3 = [ { toys: [ { toy: 'Transformers' } , { toy: 'GI Joe' }, { toy: 'He-man' } ] } ]; console.log(xml(example3)); //TransformersGI JoeHe-man console.log(xml(example3, { indent: true })); /* Transformers GI Joe He-man */ console.log('\n===== Example 4 ===='); var example4 = [ { toys: [ { _attr: { decade: '80s', locale: 'US'} }, { toy: 'Transformers' } , { toy: 'GI Joe' }, { toy: 'He-man' } ] } ]; console.log(xml(example4, { indent: true })); /* Transformers GI Joe He-man */ console.log('\n===== Example 5 ===='); var example5 = [ { toys: [ { _attr: { decade: '80s', locale: 'US'} }, { toy: 'Transformers' } , { toy: [ { _attr: { knowing: 'half the battle' } }, 'GI Joe'] }, { toy: [ { name: 'He-man' }, { description: { _cdata: 'Master of the Universe!'} } ] } ] } ]; console.log(xml(example5, { indent: true, declaration: true })); /* TransformersGI JoeHe-man Transformers GI Joe He-man Transformers GI Joe He-man Transformers GI Joe He-man Master of the Universe!]]> */ console.log('\n===== Example 6 ===='); var elem = xml.Element({ _attr: { decade: '80s', locale: 'US'} }); var xmlStream = xml({ toys: elem }, { indent: true } ); xmlStream.on('data', function (chunk) {console.log("data:", chunk)}); elem.push({ toy: 'Transformers' }); elem.push({ toy: 'GI Joe' }); elem.push({ toy: [{name:'He-man'}] }); elem.close(); /* data: data: Transformers data: GI Joe data: He-man data: */ package/examples/server.js000644 000766 000024 0000001302 11561543334014213 0ustar00000000 000000 var http = require('http'), XML = require('../lib/xml'); var server = http.createServer(function(req, res) { res.writeHead(200, {"Content-Type": "text/xml"}); var elem = XML.Element({ _attr: { decade: '80s', locale: 'US'} }); var xml = XML({ toys: elem }, {indent:true, stream:true}); res.write('\n'); xml.pipe(res); process.nextTick(function () { elem.push({ toy: 'Transformers' }); elem.push({ toy: 'GI Joe' }); elem.push({ toy: [{name:'He-man'}] }); elem.close(); }); }); server.listen(parseInt(process.env.PORT) || 3000); console.log("server listening on port %d …", server.address().port); package/lib/escapeForXML.js000644 000766 000024 0000000546 12215424252014130 0ustar00000000 000000 var XML_CHARACTER_MAP = { '&': '&', '"': '"', "'": ''', '<': '<', '>': '>' }; function escapeForXML(string) { return string && string.replace ? string.replace(/([&"<>'])/g, function(str, item) { return XML_CHARACTER_MAP[item]; }) : string; } module.exports = escapeForXML; package/lib/xml.js000644 000766 000024 0000016050 12653251752012446 0ustar00000000 000000 var escapeForXML = require('./escapeForXML'); var Stream = require('stream').Stream; var DEFAULT_INDENT = ' '; function xml(input, options) { if (typeof options !== 'object') { options = { indent: options }; } var stream = options.stream ? new Stream() : null, output = "", interrupted = false, indent = !options.indent ? '' : options.indent === true ? DEFAULT_INDENT : options.indent, instant = true; function delay (func) { if (!instant) { func(); } else { process.nextTick(func); } } function append (interrupt, out) { if (out !== undefined) { output += out; } if (interrupt && !interrupted) { stream = stream || new Stream(); interrupted = true; } if (interrupt && interrupted) { var data = output; delay(function () { stream.emit('data', data) }); output = ""; } } function add (value, last) { format(append, resolve(value, indent, indent ? 1 : 0), last); } function end() { if (stream) { var data = output; delay(function () { stream.emit('data', data); stream.emit('end'); stream.readable = false; stream.emit('close'); }); } } function addXmlDeclaration(declaration) { var encoding = declaration.encoding || 'UTF-8', attr = { version: '1.0', encoding: encoding }; if (declaration.standalone) { attr.standalone = declaration.standalone } add({'?xml': { _attr: attr } }); output = output.replace('/>', '?>'); } // disable delay delayed delay(function () { instant = false }); if (options.declaration) { addXmlDeclaration(options.declaration); } if (input && input.forEach) { input.forEach(function (value, i) { var last; if (i + 1 === input.length) last = end; add(value, last); }); } else { add(input, end); } if (stream) { stream.readable = true; return stream; } return output; } function element (/*input, …*/) { var input = Array.prototype.slice.call(arguments), self = { _elem: resolve(input) }; self.push = function (input) { if (!this.append) { throw new Error("not assigned to a parent!"); } var that = this; var indent = this._elem.indent; format(this.append, resolve( input, indent, this._elem.icount + (indent ? 1 : 0)), function () { that.append(true) }); }; self.close = function (input) { if (input !== undefined) { this.push(input); } if (this.end) { this.end(); } }; return self; } function create_indent(character, count) { return (new Array(count || 0).join(character || '')) } function resolve(data, indent, indent_count) { indent_count = indent_count || 0; var indent_spaces = create_indent(indent, indent_count); var name; var values = data; var interrupt = false; if (typeof data === 'object') { var keys = Object.keys(data); name = keys[0]; values = data[name]; if (values && values._elem) { values._elem.name = name; values._elem.icount = indent_count; values._elem.indent = indent; values._elem.indents = indent_spaces; values._elem.interrupt = values; return values._elem; } } var attributes = [], content = []; var isStringContent; function get_attributes(obj){ var keys = Object.keys(obj); keys.forEach(function(key){ attributes.push(attribute(key, obj[key])); }); } switch(typeof values) { case 'object': if (values === null) break; if (values._attr) { get_attributes(values._attr); } if (values._cdata) { content.push( ('/g, ']]]]>') + ']]>' ); } if (values.forEach) { isStringContent = false; content.push(''); values.forEach(function(value) { if (typeof value == 'object') { var _name = Object.keys(value)[0]; if (_name == '_attr') { get_attributes(value._attr); } else { content.push(resolve( value, indent, indent_count + 1)); } } else { //string content.pop(); isStringContent=true; content.push(escapeForXML(value)); } }); if (!isStringContent) { content.push(''); } } break; default: //string content.push(escapeForXML(values)); } return { name: name, interrupt: interrupt, attributes: attributes, content: content, icount: indent_count, indents: indent_spaces, indent: indent }; } function format(append, elem, end) { if (typeof elem != 'object') { return append(false, elem); } var len = elem.interrupt ? 1 : elem.content.length; function proceed () { while (elem.content.length) { var value = elem.content.shift(); if (value === undefined) continue; if (interrupt(value)) return; format(append, value); } append(false, (len > 1 ? elem.indents : '') + (elem.name ? '' : '') + (elem.indent && !end ? '\n' : '')); if (end) { end(); } } function interrupt(value) { if (value.interrupt) { value.interrupt.append = append; value.interrupt.end = proceed; value.interrupt = false; append(true); return true; } return false; } append(false, elem.indents + (elem.name ? '<' + elem.name : '') + (elem.attributes.length ? ' ' + elem.attributes.join(' ') : '') + (len ? (elem.name ? '>' : '') : (elem.name ? '/>' : '')) + (elem.indent && len > 1 ? '\n' : '')); if (!len) { return append(false, elem.indent ? '\n' : ''); } if (!interrupt(elem)) { proceed(); } } function attribute(key, value) { return key + '=' + '"' + escapeForXML(value) + '"'; } module.exports = xml; module.exports.element = module.exports.Element = element; package/readme.md000644 000766 000024 0000011306 12653254147012321 0ustar00000000 000000 # xml [![Build Status](https://api.travis-ci.org/dylang/node-xml.svg)](http://travis-ci.org/dylang/node-xml) [![NPM](https://nodei.co/npm/xml.png?downloads=true)](https://nodei.co/npm/xml/) > Fast and simple Javascript-based XML generator/builder for Node projects. ## Install $ npm install xml ## API ### `xml(xmlObject, options)` Returns a `XML` string. ```js var xml = require('xml'); var xmlString = xml(xmlObject, options); ``` #### `xmlObject` `xmlObject` is a normal JavaScript Object/JSON object that defines the data for the XML string. Keys will become tag names. Values can be an `array of xmlObjects` or a value such as a `string` or `number`. ```js xml({a: 1}) === '1' xml({nested: [{ keys: [{ fun: 'hi' }]}]}) === 'hi' ``` There are two special keys: `_attr` Set attributes using a hash of key/value pairs. ```js xml({a: [{ _attr: { attributes: 'are fun', too: '!' }}, 1]}) === '1' ```` `_cdata` Value of `_cdata` is wrapped in xml `![CDATA[]]` so the data does not need to be escaped. ```js xml({a: { _cdata: "i'm not escaped: !"}}) === '!]]>' ``` Mixed together: ```js xml({a: { _attr: { attr:'hi'}, _cdata: "I'm not escaped" }}) === '' ``` #### `options` `indent` _optional_ **string** What to use as a tab. Defaults to no tabs (compressed). For example you can use `'\t'` for tab character, or `' '` for two-space tabs. `stream` Return the result as a `stream`. **Stream Example** ```js var elem = xml.element({ _attr: { decade: '80s', locale: 'US'} }); var stream = xml({ toys: elem }, { stream: true }); stream.on('data', function (chunk) {console.log("data:", chunk)}); elem.push({ toy: 'Transformers' }); elem.push({ toy: 'GI Joe' }); elem.push({ toy: [{name:'He-man'}] }); elem.close(); /* result: data: data: Transformers data: GI Joe data: He-man data: */ ``` `Declaration` _optional_ Add default xml declaration as first node. _options_ are: * encoding: 'value' * standalone: 'value' **Declaration Example** ```js xml([ { a: 'test' }], { declaration: true }) //result: 'test' xml([ { a: 'test' }], { declaration: { standalone: 'yes', encoding: 'UTF-16' }}) //result: 'test' ``` ## Examples **Simple Example** ```js var example1 = [ { url: 'http://www.google.com/search?aq=f&sourceid=chrome&ie=UTF-8&q=opower' } ]; console.log(XML(example1)); //http://www.google.com/search?aq=f&sourceid=chrome&ie=UTF-8&q=opower ``` **Example with attributes** ```js var example2 = [ { url: { _attr: { hostname: 'www.google.com', path: '/search?aq=f&sourceid=chrome&ie=UTF-8&q=opower' } } } ]; console.log(XML(example2)); //result: ``` **Example with array of same-named elements and nice formatting** ```js var example3 = [ { toys: [ { toy: 'Transformers' } , { toy: 'GI Joe' }, { toy: 'He-man' } ] } ]; console.log(XML(example3)); //result: TransformersGI JoeHe-man console.log(XML(example3, true)); /* result: Transformers GI Joe He-man */ ``` **More complex example** ```js var example4 = [ { toys: [ { _attr: { decade: '80s', locale: 'US'} }, { toy: 'Transformers' } , { toy: 'GI Joe' }, { toy: 'He-man' } ] } ]; console.log(XML(example4, true)); /* result: Transformers GI Joe He-man */ ``` **Even more complex example** ```js var example5 = [ { toys: [ { _attr: { decade: '80s', locale: 'US'} }, { toy: 'Transformers' } , { toy: [ { _attr: { knowing: 'half the battle' } }, 'GI Joe'] }, { toy: [ { name: 'He-man' }, { description: { _cdata: 'Master of the Universe!'} } ] } ] } ]; console.log(XML(example5, true)); /* result: Transformers GI Joe He-man Master of the Universe!]]> */ ``` ## Tests Tests included use [AVA](https://ava.li). Use `npm test` to run the tests. $ npm test ## Examples There are examples in the examples directory. # Contributing Contributions to the project are welcome. Feel free to fork and improve. I accept pull requests when tests are included. package/.travis.yml000644 000766 000024 0000000126 12653253510012642 0ustar00000000 000000 sudo: false language: node_js node_js: - node - "5" - "4" - "0.10" - "0.12" package/test/xml.test.js000644 000766 000024 0000012436 12653255435013643 0ustar00000000 000000 import test from 'ava'; import xml from '../lib/xml'; test('no elements', t => { t.is(xml(), ''); t.is(xml([]), ''); t.is(xml('test'), 'test'); t.is(xml('scotch & whisky'), 'scotch & whisky'); t.is(xml('bob\'s escape character'), 'bob's escape character'); }); test('simple options', t => { t.is(xml([{a: {}}]), ''); t.is(xml([{a: null}]), ''); t.is(xml([{a: []}]), ''); t.is(xml([{a: -1}]), '-1'); t.is(xml([{a: false}]), 'false'); t.is(xml([{a: 'test'}]), 'test'); t.is(xml({a: {}}), ''); t.is(xml({a: null}), ''); t.is(xml({a: []}), ''); t.is(xml({a: -1}), '-1'); t.is(xml({a: false}), 'false'); t.is(xml({a: 'test'}), 'test'); t.is(xml([{a: 'test'}, {b: 123}, {c: -0.5}]), 'test123-0.5'); }); test('deeply nested objects', t => { t.is(xml([{a: [{b: [{c: 1}, {c: 2}, {c: 3}]}]}]), '123'); }); test('indents property', t => { t.is(xml([{a: [{b: [{c: 1}, {c: 2}, {c: 3}]}]}], true), '\n \n 1\n 2\n 3\n \n'); t.is(xml([{a: [{b: [{c: 1}, {c: 2}, {c: 3}]}]}], ' '), '\n \n 1\n 2\n 3\n \n'); t.is(xml([{a: [{b: [{c: 1}, {c: 2}, {c: 3}]}]}], '\t'), '\n\t\n\t\t1\n\t\t2\n\t\t3\n\t\n'); t.is(xml({guid: [{_attr: {premalink: true}}, 'content']}, true), 'content'); }); test('supports xml attributes', t => { t.is(xml([{b: {_attr: {}}}]), ''); t.is(xml([{ a: { _attr: { attribute1: 'some value', attribute2: 12345 } } }]), ''); t.is(xml([{ a: [{ _attr: { attribute1: 'some value', attribute2: 12345 } }] }]), ''); t.is(xml([{ a: [{ _attr: { attribute1: 'some value', attribute2: 12345 } }, 'content'] }]), 'content'); }); test('supports cdata', t => { t.is(xml([{a: {_cdata: 'This is some CDATA'}}]), 'CDATA]]>'); t.is(xml([{ a: { _attr: {attribute1: 'some value', attribute2: 12345}, _cdata: 'This is some CDATA' } }]), 'CDATA]]>'); t.is(xml([{a: {_cdata: 'This is some CDATA with ]]> and then again ]]>'}}]), 'CDATA with ]]]]> and then again ]]]]>]]>'); }); test('supports encoding', t => { t.is(xml([{ a: [{ _attr: { anglebrackets: 'this is strong', url: 'http://google.com?s=opower&y=fun' } }, 'text'] }]), 'text'); }); test('supports stream interface', t => { const elem = xml.element({_attr: {decade: '80s', locale: 'US'}}); const xmlStream = xml({toys: elem}, {stream: true}); const results = ['', 'Transformers', 'He-man', 'GI Joe', '']; elem.push({toy: 'Transformers'}); elem.push({toy: [{name: 'He-man'}]}); elem.push({toy: 'GI Joe'}); elem.close(); xmlStream.on('data', stanza => { t.is(stanza, results.shift()); }); return new Promise( (resolve, reject) => { xmlStream.on('close', () => { t.same(results, []); resolve(); }); xmlStream.on('error', reject); }); }); test('streams end properly', t => { const elem = xml.element({ _attr: { decade: '80s', locale: 'US'} }); const xmlStream = xml({ toys: elem }, { stream: true }); let gotData; t.plan(7); elem.push({ toy: 'Transformers' }); elem.push({ toy: 'GI Joe' }); elem.push({ toy: [{name:'He-man'}] }); elem.close(); xmlStream.on('data', data => { t.ok(data); gotData = true; }); xmlStream.on('end', () => { t.ok(gotData); }); return new Promise( (resolve, reject) => { xmlStream.on('close', () => { t.ok(gotData); resolve(); }); xmlStream.on('error', reject); }); }); test('xml declaration options', t => { t.is(xml([{a: 'test'}], {declaration: true}), 'test'); t.is(xml([{a: 'test'}], {declaration: {encoding: 'foo'}}), 'test'); t.is(xml([{a: 'test'}], {declaration: {standalone: 'yes'}}), 'test'); t.is(xml([{a: 'test'}], {declaration: false}), 'test'); t.is(xml([{a: 'test'}], {declaration: true, indent: '\n'}), '\ntest'); t.is(xml([{a: 'test'}], {}), 'test'); });