Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable setting attributes when building obj with array #625

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions lib/builder.js

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

10 changes: 8 additions & 2 deletions src/builder.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,14 @@ class exports.Builder
else if Array.isArray obj
# fix issue #119
for own index, child of obj
for key, entry of child
element = render(element.ele(key), entry).up()
# allow setting attributes for parents with multiple childrens
if index is attrkey
if typeof child is "object"
for attr, value of child
element = element.att(attr, value)
else
for key, entry of child
element = render(element.ele(key), entry).up()
else
for own key, child of obj
# Case #1 Attribute
Expand Down
17 changes: 17 additions & 0 deletions test/builder.test.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -281,3 +281,20 @@ module.exports =
actual = builder.buildObject obj
diffeq expected, actual
test.finish()

'test building obj with array and attributes': (test) ->
expected = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root name="myName">
<MsgId>10</MsgId>
<MsgId2>12</MsgId2>
</root>

"""
opts = cdata: true
builder = new xml2js.Builder opts
obj = [{"MsgId": 10}, {"MsgId2": 12}]
obj.$ = {"name": "myName"}
actual = builder.buildObject obj
diffeq expected, actual
test.finish()