1

I am creating an xml file using "xml-builder" node module. But when I tried to write angle brackets ("<" or ">"), I got characters like "<" and ">". The code is as follows:

let builder = require('xmlbuilder', { encoding: 'utf-8' });
let name = "ABC";
let xml = builder.create('Slides');
xml.ele('props',"Hello").up();
xml.ele('name',"<Hello> "+name+" </Hello>").up();
xml.end({ pretty: true });
console.log(xml.toString())

The output is as follows:

<Slides>
  <props>Hello</props>
  <name>&lt;Hello&gt; ABC &lt;/Hello&gt;</name>
</Slides>

What should I do to get < or > printed instead of &lt; or &gt; ?

mihai
  • 37,072
  • 9
  • 60
  • 86

2 Answers2

0

There is an npm module decode-html that will handle the same use case as your.

var decode = require('decode-html');

console.log(decode('&lt;div class="hidden"&gt;NON&amp;SENSE&apos;s&lt;/div&gt;'));
// -> '<div class="hidden">NON&SENSE\'s</div>'
front_end_dev
  • 1,998
  • 1
  • 9
  • 14
0

The problem is that is you are attempting to create a child element in an incorrect way, by passing some xml in the value field of xml.ele. The module is correctly escaping your angle brackets.

What you need to do is create another element named Hello and append it to the name element. You can do this by either chaining your .ele calls or using their return values.

Here is the correct code:

let builder = require('xmlbuilder', { encoding: 'utf-8' });
let name = "ABC";
let xml = builder.create('Slides');
xml.ele('props',"Hello");
xml.ele('name')
   .ele("Hello", name);
xml.end({ pretty: true });
console.log(xml.toString())

Output:

<Slides>
  <props>Hello</props>
  <name>
    <Hello>ABC</Hello>
  </name>
</Slides>
mihai
  • 37,072
  • 9
  • 60
  • 86
  • Sir, actually I have to create "cdata" section in the xml file. Ex: "<![CDATA[{Notes Text}]]>". How to create that cdata section? – Kushagra Sinha Nov 10 '18 at 10:36
  • See https://github.com/oozcitak/xmlbuilder-js/wiki#cdata-nodes or ask a different question – mihai Nov 10 '18 at 10:39