From 77f8aa33afa182b32fc915f5ef5693a367ade6a2 Mon Sep 17 00:00:00 2001 From: Andreas Naziris Date: Mon, 6 May 2024 11:07:42 +0300 Subject: [PATCH] fix #634: build attributes with oneListGroup and attributesGroupName Don't ignore attributes when building to xml with oneListGroup and attributesGroupName enabled. --- spec/j2x_spec.js | 24 ++++++++++++++++++++++++ src/xmlbuilder/json2xml.js | 11 ++++++++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/spec/j2x_spec.js b/spec/j2x_spec.js index 79ec6ecb..8e89358e 100644 --- a/spec/j2x_spec.js +++ b/spec/j2x_spec.js @@ -482,6 +482,30 @@ describe("XMLBuilder", function() { const expected = `12`; 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 = { diff --git a/src/xmlbuilder/json2xml.js b/src/xmlbuilder/json2xml.js index 5707ee0f..f1ff3a97 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) } @@ -134,7 +139,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 {