Skip to content

Commit 82b2fd7

Browse files
Added support for inserting several nodes from an array
1 parent 48d4710 commit 82b2fd7

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "njs-tfso-xml",
3-
"version": "1.2.0",
3+
"version": "1.3.0",
44
"main": "./index.js",
55
"scripts": {
66
"test": "mocha --recursive ./test/**/test*"

src/XmlWriter.js

+27
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,33 @@ class XmlWriter{
7676
return this
7777
}
7878

79+
/**
80+
* Ex:
81+
* // simple element creation
82+
* writer.adds('node', ['a','b'])
83+
* <node>a<node>
84+
* <node>b<node>
85+
* // or a custom element creation
86+
* writer.adds('node', ['a','b'], (node, str) => node
87+
* .add('Id', str)
88+
* )
89+
* <node><Id>a</Id><node>
90+
* <node><Id>b</Id><node>
91+
* @param {string} path
92+
* @param {Array} values
93+
* @param {elementCallback|*} valueOrFunctionOrNull
94+
* @param {Object|null} attributes
95+
* @returns {XmlWriter}
96+
*/
97+
adds(path, values, valueOrFunctionOrNull = null, attributes = null){
98+
valueOrFunctionOrNull = valueOrFunctionOrNull || ((writer, value) => writer.setVal(value))
99+
values.forEach(value =>{
100+
this.addAndGet(path, (writer) => valueOrFunctionOrNull(writer, value), attributes)
101+
})
102+
103+
return this
104+
}
105+
79106
/**
80107
* @param {string} path
81108
* @param {elementCallback|*} valueOrFunctionOrNull

test/testXmlWriter.js

+17
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,21 @@ describe('XmlWriter', () => {
4747

4848
chai.expect(reader.valAt('test')).to.equal('hello!')
4949
})
50+
51+
it('should inject several simple values', async () => {
52+
const writer = XmlWriter.create('', '', '', 'Document')
53+
54+
writer.adds('node', ['a', 'b'])
55+
56+
chai.expect(writer.toString()).to.deep.equal('<?xml version="1.0" encoding="utf-8"?><Document><node>a</node><node>b</node></Document>')
57+
})
58+
59+
it('should inject several custom values with attributes', async () => {
60+
const writer = XmlWriter.create('', '', '', 'Document')
61+
62+
const items = ['a', 'b']
63+
writer.adds('node', items, (node, item)=> node.add('id', item), {prop:'yo'})
64+
65+
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>')
66+
})
5067
})

0 commit comments

Comments
 (0)