From acf610f25d75ece793c4e24b4673e60871c04341 Mon Sep 17 00:00:00 2001 From: a-rasin <90502898+a-rasin@users.noreply.github.com> Date: Wed, 10 Jul 2024 11:19:20 +0300 Subject: [PATCH] fix #634: build attributes with oneListGroup and attributesGroupName (#653) Don't ignore attributes when building to xml with oneListGroup and attributesGroupName enabled. Co-authored-by: Andreas Naziris --- 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 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 {