Skip to content

Commit

Permalink
fix: preserveChildrenOrder without explicitChildren
Browse files Browse the repository at this point in the history
  • Loading branch information
ds82 committed Jun 26, 2015
1 parent f606e9f commit 4179b44
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 9 deletions.
2 changes: 1 addition & 1 deletion lib/bom.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/processors.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 40 additions & 6 deletions lib/xml2js.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 26 additions & 1 deletion src/xml2js.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ exports.defaults =
chunkSize: 10000
emptyTag: ''
cdata: false
sortkey: '#index'

class exports.ValidationError extends Error
constructor: (message) ->
Expand All @@ -112,6 +113,7 @@ class exports.Builder
buildObject: (rootObj) ->
attrkey = @options.attrkey
charkey = @options.charkey
sortkey = @options.sortkey

# If there is a sane-looking first element to use as the root,
# and the user hasn't specified a non-default rootName,
Expand All @@ -124,6 +126,8 @@ class exports.Builder
rootName = @options.rootName

render = (element, obj) =>
list = [];

if typeof obj isnt 'object'
# single element, just append it as text
if @options.cdata && requiresCDATA obj
Expand All @@ -146,8 +150,25 @@ class exports.Builder
else
element = element.txt child

else if key is sortkey
# console.log(key)
# noop
else
if Array.isArray child
for own index, entry of child
list.push {key:key, child:entry}
else
list.push {key:key, child: child}

list.sort (a, b) ->
return (a.child[sortkey] || -1) - (b.child[sortkey] || -1)

for own index, entry of list
key = entry.key
child = entry.child

# Case #3 Array data
else if Array.isArray child
if Array.isArray child
for own index, entry of child
if typeof entry is 'string'
if @options.cdata && requiresCDATA entry
Expand Down Expand Up @@ -334,6 +355,10 @@ class exports.Parser extends events.EventEmitter
if Object.keys(obj).length == 1 and charkey of obj and not @EXPLICIT_CHARKEY
obj = obj[charkey]

else if @options.preserveChildrenOrder
index = if s then Math.max(Object.keys(s).length - 2, 0) else 0
obj[@options.sortkey] = index

# check whether we closed all the open tags
if stack.length > 0
@assignOrPush s, nodeName, obj
Expand Down

0 comments on commit 4179b44

Please sign in to comment.