Skip to content

Commit

Permalink
fix(xml2js): Attributes were lost when keepCData property was true #73
Browse files Browse the repository at this point in the history
  • Loading branch information
FLAHOU Maxime committed May 17, 2018
1 parent 63adc54 commit c046e35
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
6 changes: 6 additions & 0 deletions tests_xml2js.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
'<elementY>hello there</elementY>' +
'<elementZ><![CDATA[hello again]]></elementZ>' +
'<elementZA>Test<![CDATA[ hello again]]></elementZA>' +
'<elementZB attribute="value"><![CDATA[hello again]]></elementZB>' +
'</document>';
var x = new X2JS();
var js = x.xml2js(xml);
Expand All @@ -51,6 +52,11 @@
assert.ok(js.document.elementZA);
assert.strictEqual(js.document.elementZA.toString(), 'Test hello again');
assert.strictEqual(js.document.elementZA.__cdata, ' hello again');

assert.ok(js.document.elementZB);
assert.strictEqual(js.document.elementZB.toString(), 'hello again');
assert.strictEqual(js.document.elementZB._attribute, 'value');
assert.strictEqual(js.document.elementZB.__cdata, 'hello again');
});

QUnit.test('XML with namespace prefixes', function (assert) {
Expand Down
7 changes: 6 additions & 1 deletion x2js.js
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,12 @@
}
delete result.__cnt;

if (!config.keepCData && (!result.hasOwnProperty('__text') && result.hasOwnProperty('__cdata'))) {
/**
* We are checking if we are creating a __cdata property or if we just add the content of cdata inside result.
* But, if we have a property inside xml tag (<tag PROPERTY="1"></tag>), and a cdata inside, we can't ignore it.
* In this case we are keeping __cdata property.
*/
if (!config.keepCData && (!result.hasOwnProperty('__text') && result.hasOwnProperty('__cdata') && Object.keys(result).length === 1)) {
return (result.__cdata ? result.__cdata : '');
}

Expand Down

0 comments on commit c046e35

Please sign in to comment.