Skip to content

Commit

Permalink
Added support for inserting several nodes from an array
Browse files Browse the repository at this point in the history
  • Loading branch information
edgarbjorntvedt committed Mar 6, 2020
1 parent 48d4710 commit 82b2fd7
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "njs-tfso-xml",
"version": "1.2.0",
"version": "1.3.0",
"main": "./index.js",
"scripts": {
"test": "mocha --recursive ./test/**/test*"
Expand Down
27 changes: 27 additions & 0 deletions src/XmlWriter.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,33 @@ class XmlWriter{
return this
}

/**
* Ex:
* // simple element creation
* writer.adds('node', ['a','b'])
* <node>a<node>
* <node>b<node>
* // or a custom element creation
* writer.adds('node', ['a','b'], (node, str) => node
* .add('Id', str)
* )
* <node><Id>a</Id><node>
* <node><Id>b</Id><node>
* @param {string} path
* @param {Array} values
* @param {elementCallback|*} valueOrFunctionOrNull
* @param {Object|null} attributes
* @returns {XmlWriter}
*/
adds(path, values, valueOrFunctionOrNull = null, attributes = null){
valueOrFunctionOrNull = valueOrFunctionOrNull || ((writer, value) => writer.setVal(value))
values.forEach(value =>{
this.addAndGet(path, (writer) => valueOrFunctionOrNull(writer, value), attributes)
})

return this
}

/**
* @param {string} path
* @param {elementCallback|*} valueOrFunctionOrNull
Expand Down
17 changes: 17 additions & 0 deletions test/testXmlWriter.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,21 @@ describe('XmlWriter', () => {

chai.expect(reader.valAt('test')).to.equal('hello!')
})

it('should inject several simple values', async () => {
const writer = XmlWriter.create('', '', '', 'Document')

writer.adds('node', ['a', 'b'])

chai.expect(writer.toString()).to.deep.equal('<?xml version="1.0" encoding="utf-8"?><Document><node>a</node><node>b</node></Document>')
})

it('should inject several custom values with attributes', async () => {
const writer = XmlWriter.create('', '', '', 'Document')

const items = ['a', 'b']
writer.adds('node', items, (node, item)=> node.add('id', item), {prop:'yo'})

chai.expect(writer.toString()).to.deep.equal('<?xml version="1.0" encoding="utf-8"?><Document><node prop="yo"><id>a</id></node><node prop="yo"><id>b</id></node></Document>')
})
})

0 comments on commit 82b2fd7

Please sign in to comment.