Skip to content

CDATA is written with indentation and newlines #14

@Hagedihag

Description

@Hagedihag

I read the following XML with xml2json:

<?xml version="1.0"?>
<group>
	<name><![CDATA[An example name]]></name>
</group>

but writing it back with json2xml gives me:

<?xml version="1.0"?>
<group>
    <name>
        <![CDATA[My modified name]]>
    </name>
</group>

This is is not the expected XML output.
The CDATA section is not a TAG and should not be handled as one and therefore not be indented.
Sure, its easier to read, but its not 100% correct.
It would be great to fix that or make a config parameter for that behaviour.

example code:

var xmljs = require('xml-js');
var xmlIn = '<?xml version="1.0"?>\n<group>\n\t<name><![CDATA[An example name]]></name>\n</group>';
console.log('xmlIn:\n',xmlIn);

var jsonIn = xmljs.xml2json(xmlIn, {
	compact: true
});
var obj = JSON.parse(jsonIn);

// code to modify obj
obj.group.name._cdata = 'My modified name';

var jsonOut = JSON.stringify(obj);

var xmlOut = xmljs.json2xml(jsonOut, {
	compact	: true, 
	spaces	: 4,
	fullTagEmptyElement: true
});

console.log('xmlOut:\n',xmlOut);

Solution
file: js2xml.js

  1. Function: writeElementsCompact, Line 143
                case options.cdataKey: xml += writeCdata(element, options); break;
  1. Function: hasContent, Line 102
                case options.cdataKey:
                	return false;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions