diff --git a/spec/j2x_spec.js b/spec/j2x_spec.js index 73209f6a..828c12cd 100644 --- a/spec/j2x_spec.js +++ b/spec/j2x_spec.js @@ -496,6 +496,30 @@ describe("XMLBuilder", function() { expect(result).toEqual(expected); }); + it("should handle attributes with oneListGroup", function() { + const jObj = { + "a": [ + { + "b": "1" + }, + { + "b": "2" + }, + { + "@": { + "foo": "bar", + "baz": "foo", + "bar": "baz" + } + } + ], + }; + const builder = new XMLBuilder({oneListGroup:"true", attributesGroupName: "@"}); + const result = builder.build(jObj); + const expected = `12`; + expect(result).toEqual(expected); + }); + it('should build tag with only text node', async () => { const schema_obj = { field: { diff --git a/src/xmlbuilder/json2xml.js b/src/xmlbuilder/json2xml.js index 6fe3f60c..f30604a4 100644 --- a/src/xmlbuilder/json2xml.js +++ b/src/xmlbuilder/json2xml.js @@ -115,6 +115,7 @@ Builder.prototype.j2x = function(jObj, level) { //repeated nodes const arrLen = jObj[key].length; let listTagVal = ""; + let listTagAttr = ""; for (let j = 0; j < arrLen; j++) { const item = jObj[key][j]; if (typeof item === 'undefined') { @@ -124,8 +125,12 @@ Builder.prototype.j2x = function(jObj, level) { else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; } else if (typeof item === 'object') { - if(this.options.oneListGroup ){ - listTagVal += this.j2x(item, level + 1).val; + if(this.options.oneListGroup){ + const result = this.j2x(item, level + 1); + listTagVal += result.val; + if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { + listTagAttr += result.attrStr + } }else{ listTagVal += this.processTextOrObjNode(item, key, level) } @@ -140,7 +145,7 @@ Builder.prototype.j2x = function(jObj, level) { } } if(this.options.oneListGroup){ - listTagVal = this.buildObjectNode(listTagVal, key, '', level); + listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); } val += listTagVal; } else {