mrNasty
mrNasty

Reputation: 3

How to add html tags in CDATA of xml2js xml?

I'm trying to build a XML node with xml2js. When I add html tags wrapped in cdata, it creates a separate node as shown below. And if I wrap the CDATA inside "<>" the value inside gets undefined. Basically I'm trying to create XML documents from which I can take the node values and show it in the HTML documents using jQuery/Angular. And those node must be able to contain HTML tags

var xml2js = require('xml2js');

var parser = new xml2js.Parser({
    explicitArray: false
});
var builder = new xml2js.Builder({
    cdata: true
});


var test = "<parent>![CDATA[Hey There! <span> Buddy.</span>]]</parent>"

parser.parseString(test, function(err, result) {
    var xml = builder.buildObject(result)
    console.log(xml)
});
//Output
/*
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent>
  ![CDATA[Hey There! ]]
  <span> Buddy.</span>
</parent>
*/


var test2 = "<parent><![CDATA['Hey There! <span> Buddy.</span>']]></parent>";

parser.parseString(test, function(err, result) {
    var xml = builder.buildObject(result)
    console.log(xml)
});
//Output : 
/*
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent><![CDATA[undefined]]></parent>
*/

Upvotes: 0

Views: 3747

Answers (2)

Abner Tellez Sazo
Abner Tellez Sazo

Reputation: 64

It could be made without the Parser. _ helps to handle the inner text inside tags.

const xml2js = require('xml2js');

const builder = new xml2js.Builder({
    cdata: true
});

const test = "Hey There! <span> Buddy.</span>";

const xml = builder.buildObject({
   parent: {
     _: test,
   }
});

console.log(xml);

Upvotes: 0

trevor
trevor

Reputation: 2300

Your first test was almost correct. You actually needed the < > symbols around the CDATA content.

This code:

var xml2js = require('xml2js');

var parser = new xml2js.Parser({
    explicitArray: false
});
var builder = new xml2js.Builder({
    cdata: true
});

var test = "<parent><![CDATA[Hey There! <span> Buddy.</span>]]></parent>";

parser.parseString(test, function(err, result) {
    var xml = builder.buildObject(result);
    console.log(xml);
});

Produces this output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent><![CDATA[Hey There! <span> Buddy.</span>]]></parent>

Upvotes: 2

Related Questions