Open In App

How to Escape Characters in XML ?

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Escaping characters in XML is important because it ensures that special characters like <, >, &, and “, which have special meanings in XML, are properly encoded as entities like &lt;, &gt;, &amp;, &quot;, respectively.

There are several approaches to escape characters in XML which are as follows:

Using replace() Method

In this approach, we are using the replace() method with a regular expression to search for characters <, >, “, ‘, and & in the XML data and replace them with their respective XML entities (&lt;, &gt;, &quot;, &apos;, &amp;).

Example: The below example uses the replace() method to escape characters in XML.

JavaScript
function escapeFn(xmlData) {
    return xmlData.replace(/[<>"'&]/g, function (char) {
        switch (char) {
            case '<':
                return '&lt;';
            case '>':
                return '&gt;';
            case '"':
                return '&quot;';
            case '\'':
                return '&apos;';
            case '&':
                return '&amp;';
        }
    });
}
const xmlData = `
<article>
  <title>XML Tutorial</title>
  <author>GeeksforGeeks</author>
  <body>
    Hi Geeks!
  </body>
</article>
`;
const res = escapeFn(xmlData);
console.log(res);

Output
&lt;article&gt;
  &lt;title&gt;XML Tutorial&lt;/title&gt;
  &lt;author&gt;GeeksforGeeks&lt;/author&gt;
  &lt;body&gt;
    Hi Geeks!
  &lt;/body&gt;
&lt;/article&gt;

Using xml-escape Library

In this approach, we are using the XML-escape library, which provides a simple function xmlEscape to escape XML characters like <, >, &, and “. It automatically converts these characters into their respective XML entities (&lt;, &gt;, &amp;, &quot;) in the given XML input.

Use the below command to install the xml-escape library:

npm install xml-escape

Example: The below example uses the XML-escape Library to escape characters in XML.

JavaScript
const xmlEscape = require('xml-escape');
const xmlInput = `
<article>
  <title>XML Tutorial</title>
  <author>GeeksforGeeks</author>
  <body>
    Hi Geeks!
  </body>
</article>
`;
const res = xmlEscape(xmlInput);
console.log(res);

Output:

&lt;article&gt;
&lt;title&gt;XML Tutorial&lt;/title&gt;
&lt;author&gt;GeeksforGeeks&lt;/author&gt;
&lt;body&gt;
Hi Geeks!
&lt;/body&gt;
&lt;/article&gt;

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads