Skip to content

Commit 1832e0b

Browse files
Merge pull request #512 from economia/master
Allow function as default value for parsing empty tags
2 parents 198063c + fa32064 commit 1832e0b

File tree

5 files changed

+21
-3
lines changed

5 files changed

+21
-3
lines changed

README.md

+4-1
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,10 @@ value})``. Possible options are:
331331
* `normalize` (default: `false`): Trim whitespaces inside text nodes.
332332
* `explicitRoot` (default: `true`): Set this if you want to get the root
333333
node in the resulting object.
334-
* `emptyTag` (default: `''`): what will the value of empty nodes be.
334+
* `emptyTag` (default: `''`): what will the value of empty nodes be. In case
335+
you want to use an empty object as a default value, it is better to provide a factory
336+
function `() => ({})` instead. Without this function a plain object would
337+
become a shared reference across all occurrences with unwanted behavior.
335338
* `explicitArray` (default: `true`): Always put child nodes in an array if
336339
true; otherwise an array is created only if there is more than one.
337340
* `ignoreAttrs` (default: `false`): Ignore all XML attributes and only create

lib/parser.js

+5-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/parser.coffee

+4-1
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,10 @@ class exports.Parser extends events
145145
obj = obj[charkey]
146146

147147
if (isEmpty obj)
148-
obj = if @options.emptyTag != '' then @options.emptyTag else emptyStr
148+
if typeof @options.emptyTag == 'function'
149+
obj = @options.emptyTag()
150+
else
151+
obj = if @options.emptyTag != '' then @options.emptyTag else emptyStr
149152

150153
if @options.validator?
151154
xpath = "/" + (node["#name"] for node in stack).concat(nodeName).join("/")

test/fixtures/sample.xml

+3
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,7 @@
5555
<tagNameProcessTest/>
5656
<valueProcessTest>some value</valueProcessTest>
5757
<textordertest>this is text with <b>markup</b> <em>like this</em> in the middle</textordertest>
58+
<emptytestanother>
59+
60+
</emptytestanother>
5861
</sample>

test/parser.test.coffee

+5
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,11 @@ module.exports =
8383
# determine number of items in object
8484
equ Object.keys(r.sample.tagcasetest[0]).length, 3)
8585

86+
'test parse with empty objects and functions': skeleton({emptyTag: ()=> ({})}, (r)->
87+
console.log 'Result object: ' + util.inspect r, false, 10
88+
bool = r.sample.emptytestanother[0] is r.sample.emptytest[0]
89+
equ bool, false)
90+
8691
'test parse with explicitCharkey': skeleton(explicitCharkey: true, (r) ->
8792
console.log 'Result object: ' + util.inspect r, false, 10
8893
equ r.sample.chartest[0].$.desc, 'Test for CHARs'

0 commit comments

Comments
 (0)