1

In NodeJS by using xml2js module I am converting the XML string to JSON object and after some edit again converting that JSON object back into XML. All this is working well however the problem is that CDATA tags are missing in the converted XML. Can someone help me with this? I am giving the sample code below which has the same issue.

var xml2js = require('xml2js');
var parser = new xml2js.Parser();
parser.parseString("<myxml myattribute='value'><![CDATA[Hello again]]>
</myxml>", function (err, data) {   

var builder = new xml2js.Builder({
cdata: true
});
var xml = builder.buildObject(data);
 console.log(" ------------ "+xml);
});

Thanks -kt

KT B
  • 75
  • 1
  • 9
  • Please change the title to "NodeJS xml2js - removes CDATA tag while converting from XML to JSON" – Smile4ever May 12 '17 at 11:43
  • Why do you need CDATA? – Smile4ever May 12 '17 at 11:44
  • I have lots of XML where CDATA is used. I am developing application to edit those xml and save the updated xml. Hence need to keep the xml structure as it is. – KT B May 12 '17 at 11:48
  • 1
    Do you know what CDATA does? Do you know why it might be removed? (I.e., do you know why it might not matter that it is removed?) See http://stackoverflow.com/questions/2784183/what-does-cdata-in-xml-mean – Cody G May 12 '17 at 12:37
  • @Cody.G: I have some html tags and few array code in the xml as a content hence it is added in CDATA tag. As I said above I need to keep the xml structure (with CDATA) as it is while editing the xml and saving it. I noticed that while parsing the XML string and converting it into JSON object the CDATA tags get removed. – KT B May 12 '17 at 13:44
  • Can you provide an example in your question where the tags are required but get removed? – Cody G May 12 '17 at 14:34
  • CDATA is not required for your example. – Cody G May 13 '17 at 12:45
  • @Cody G: ha ha ha this is funny...I had given example so that one can check the issue. Ofcourse I know that CDATA is not required here..... – KT B May 14 '17 at 06:23
  • I'm saying to update your question with the "html tags and few array code" instead of "Hello again" – Cody G May 14 '17 at 13:31

1 Answers1

3

Please read https://github.com/Leonidas-from-XIV/node-xml2js/issues/218

Per the package author, per wikipedia:

A CDATA section is merely an alternative syntax for expressing character data; there is no semantic difference between character data that manifests as a CDATA section and character data that manifests as in the usual syntax in which "<" and "&" would be represented by "<" and "&", respectively.

The documentation states for the option cdata:

cdata (default: false): wrap text nodes in instead of escaping when necessary. Does not add if it is not required. Added in 0.4.5.

Cody G
  • 6,752
  • 2
  • 28
  • 40