Skip to content

Commit

Permalink
support numeric values and false-y attributes
Browse files Browse the repository at this point in the history
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: <tag>3.14</tag>

(see Inist-CNRS#5)
  • Loading branch information
Chip Lee committed Sep 16, 2014
1 parent 0877a26 commit c853fdd
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 20 additions & 1 deletion lib/xml-writer.js
Original file line number Diff line number Diff line change
@@ -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();
}
Expand Down Expand Up @@ -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();
},

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
},
{
"name": "Chip Lee",
"url": "https://github.com/chiplee"
"url": "https://github.com/chipincode"
},
{
"name": "Peecky",
Expand Down
8 changes: 8 additions & 0 deletions test/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,11 @@ exports['t06'] = function (test) {
test.equal(this.xw.toString(), '<tag key="&quot;&lt; &amp; &gt;&quot;"/>');
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(), '<tag/>');
test.done();
};

0 comments on commit c853fdd

Please sign in to comment.