Skip to content

Commit acf610f

Browse files
a-rasinAndreas Naziris
and
Andreas Naziris
authored
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 <[email protected]>
1 parent 931e910 commit acf610f

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

spec/j2x_spec.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,6 +496,30 @@ describe("XMLBuilder", function() {
496496
expect(result).toEqual(expected);
497497
});
498498

499+
it("should handle attributes with oneListGroup", function() {
500+
const jObj = {
501+
"a": [
502+
{
503+
"b": "1"
504+
},
505+
{
506+
"b": "2"
507+
},
508+
{
509+
"@": {
510+
"foo": "bar",
511+
"baz": "foo",
512+
"bar": "baz"
513+
}
514+
}
515+
],
516+
};
517+
const builder = new XMLBuilder({oneListGroup:"true", attributesGroupName: "@"});
518+
const result = builder.build(jObj);
519+
const expected = `<a foo="bar" baz="foo" bar="baz"><b>1</b><b>2</b></a>`;
520+
expect(result).toEqual(expected);
521+
});
522+
499523
it('should build tag with only text node', async () => {
500524
const schema_obj = {
501525
field: {

src/xmlbuilder/json2xml.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ Builder.prototype.j2x = function(jObj, level) {
115115
//repeated nodes
116116
const arrLen = jObj[key].length;
117117
let listTagVal = "";
118+
let listTagAttr = "";
118119
for (let j = 0; j < arrLen; j++) {
119120
const item = jObj[key][j];
120121
if (typeof item === 'undefined') {
@@ -124,8 +125,12 @@ Builder.prototype.j2x = function(jObj, level) {
124125
else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
125126
// val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
126127
} else if (typeof item === 'object') {
127-
if(this.options.oneListGroup ){
128-
listTagVal += this.j2x(item, level + 1).val;
128+
if(this.options.oneListGroup){
129+
const result = this.j2x(item, level + 1);
130+
listTagVal += result.val;
131+
if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
132+
listTagAttr += result.attrStr
133+
}
129134
}else{
130135
listTagVal += this.processTextOrObjNode(item, key, level)
131136
}
@@ -140,7 +145,7 @@ Builder.prototype.j2x = function(jObj, level) {
140145
}
141146
}
142147
if(this.options.oneListGroup){
143-
listTagVal = this.buildObjectNode(listTagVal, key, '', level);
148+
listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level);
144149
}
145150
val += listTagVal;
146151
} else {

0 commit comments

Comments
 (0)