From c853fdd88aab1a971c47a0eb7a5bf9c34fe48995 Mon Sep 17 00:00:00 2001 From: Chip Lee Date: Tue, 16 Sep 2014 15:57:39 -0700 Subject: [PATCH] support numeric values and false-y attributes added support for using numeric values in attributes and element text added support for suppressing attribute if the value is false-y xw.startElement('tag') .writeAttribute('key1', false) .writeAttribute('key2', null) .writeAttribute('key3', undefined) .text(3.14) .endElement(); results in: 3.14 (see https://github.com/touv/node-xml-writer/issues/5) --- README.md | 2 +- lib/xml-writer.js | 21 ++++++++++++++++++++- package.json | 2 +- test/attributes.js | 8 ++++++++ 4 files changed, 30 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1ee2793..64cefaf 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ XML is still valid. * [Nicolas Thouvenin](https://github.com/touv) * [Anton Zem](https://github.com/AlgoTrader) - * [Chip Lee](https://github.com/chiplee) + * [Chip Lee](https://github.com/chipincode) * [Peecky](https://github.com/peecky) # Installation diff --git a/lib/xml-writer.js b/lib/xml-writer.js index 24925cb..4ce476c 100644 --- a/lib/xml-writer.js +++ b/lib/xml-writer.js @@ -1,8 +1,15 @@ +function isFalse(s) { + return typeof s !== 'number' && !s; +} + function strval(s) { if (typeof s == 'string') { return s; - } + } + else if (typeof s == 'number') { + return s+''; + } else if (typeof s == 'function') { return s(); } @@ -177,12 +184,24 @@ XMLWriter.prototype = { }, writeAttribute : function (name, content) { + if (typeof content == 'function') { + content = content(); + } + if (isFalse(content)) { + return this; + } return this.startAttribute(name).text(content).endAttribute(); }, writeAttributeNS : function (prefix, name, uri, content) { if (!content) { content = uri; } + if (typeof content == 'function') { + content = content(); + } + if (isFalse(content)) { + return this; + } return this.startAttributeNS(prefix, name, uri).text(content).endAttribute(); }, diff --git a/package.json b/package.json index 0c95c2e..825ef9e 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ }, { "name": "Chip Lee", - "url": "https://github.com/chiplee" + "url": "https://github.com/chipincode" }, { "name": "Peecky", diff --git a/test/attributes.js b/test/attributes.js index 0e2120f..ab40201 100644 --- a/test/attributes.js +++ b/test/attributes.js @@ -56,3 +56,11 @@ exports['t06'] = function (test) { test.equal(this.xw.toString(), ''); test.done(); }; +exports['t07'] = function (test) { + this.xw.startElement('tag'); + this.xw.writeAttribute('key1', false); + this.xw.writeAttribute('key2', null); + this.xw.writeAttribute('key3', undefined); + test.equal(this.xw.toString(), ''); + test.done(); +};