Skip to content

Commit

Permalink
fix #634: build attributes with oneListGroup and attributesGroupName (#…
Browse files Browse the repository at this point in the history
…653)

Don't ignore attributes when building to xml with oneListGroup and
attributesGroupName enabled.

Co-authored-by: Andreas Naziris <andreas.naziris@converlens.com>
  • Loading branch information
a-rasin and Andreas Naziris committed Jul 10, 2024
1 parent 931e910 commit acf610f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
24 changes: 24 additions & 0 deletions spec/j2x_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = `<a foo="bar" baz="foo" bar="baz"><b>1</b><b>2</b></a>`;
expect(result).toEqual(expected);
});

it('should build tag with only text node', async () => {
const schema_obj = {
field: {
Expand Down
11 changes: 8 additions & 3 deletions src/xmlbuilder/json2xml.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand All @@ -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)
}
Expand All @@ -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 {
Expand Down

0 comments on commit acf610f

Please sign in to comment.