diff --git a/README.md b/README.md
index 795fd3bb..5592feaa 100644
--- a/README.md
+++ b/README.md
@@ -331,7 +331,10 @@ value})``. Possible options are:
* `normalize` (default: `false`): Trim whitespaces inside text nodes.
* `explicitRoot` (default: `true`): Set this if you want to get the root
node in the resulting object.
- * `emptyTag` (default: `''`): what will the value of empty nodes be.
+ * `emptyTag` (default: `''`): what will the value of empty nodes be. In case
+ you want to use an empty object as a default value, it is better to provide a factory
+ function `() => ({})` instead. Without this function a plain object would
+ become a shared reference across all occurrences with unwanted behavior.
* `explicitArray` (default: `true`): Always put child nodes in an array if
true; otherwise an array is created only if there is more than one.
* `ignoreAttrs` (default: `false`): Ignore all XML attributes and only create
diff --git a/lib/parser.js b/lib/parser.js
index 59f4d545..eda231cb 100644
--- a/lib/parser.js
+++ b/lib/parser.js
@@ -198,7 +198,11 @@
}
}
if (isEmpty(obj)) {
- obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr;
+ if (typeof _this.options.emptyTag === 'function') {
+ obj = _this.options.emptyTag();
+ } else {
+ obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr;
+ }
}
if (_this.options.validator != null) {
xpath = "/" + ((function() {
diff --git a/src/parser.coffee b/src/parser.coffee
index 37967966..eb19c5b0 100644
--- a/src/parser.coffee
+++ b/src/parser.coffee
@@ -145,7 +145,10 @@ class exports.Parser extends events
obj = obj[charkey]
if (isEmpty obj)
- obj = if @options.emptyTag != '' then @options.emptyTag else emptyStr
+ if typeof @options.emptyTag == 'function'
+ obj = @options.emptyTag()
+ else
+ obj = if @options.emptyTag != '' then @options.emptyTag else emptyStr
if @options.validator?
xpath = "/" + (node["#name"] for node in stack).concat(nodeName).join("/")
diff --git a/test/fixtures/sample.xml b/test/fixtures/sample.xml
index 0ffea408..e25a6feb 100644
--- a/test/fixtures/sample.xml
+++ b/test/fixtures/sample.xml
@@ -55,4 +55,7 @@
some value
this is text with markup like this in the middle
+
+
+
diff --git a/test/parser.test.coffee b/test/parser.test.coffee
index 26982344..f2758759 100644
--- a/test/parser.test.coffee
+++ b/test/parser.test.coffee
@@ -83,6 +83,11 @@ module.exports =
# determine number of items in object
equ Object.keys(r.sample.tagcasetest[0]).length, 3)
+ 'test parse with empty objects and functions': skeleton({emptyTag: ()=> ({})}, (r)->
+ console.log 'Result object: ' + util.inspect r, false, 10
+ bool = r.sample.emptytestanother[0] is r.sample.emptytest[0]
+ equ bool, false)
+
'test parse with explicitCharkey': skeleton(explicitCharkey: true, (r) ->
console.log 'Result object: ' + util.inspect r, false, 10
equ r.sample.chartest[0].$.desc, 'Test for CHARs'