"), I got characters like "<" and ">". T" /> "), I got characters like "<" and ">". T" /> "), I got characters like "<" and ">". T"/>

Problem in printing angle brackets using the xml-builder node module

324 Views Asked by At

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; ?

2

There are 2 best solutions below

1
front_end_dev On

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>'
2
mihai On

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>