How to Escape Characters in XML ?
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 <, >, &, ", respectively.
There are several approaches to escape characters in XML which are as follows:
Table of Content
- Using replace() Method
- Using xml-escape Library
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 (<, >, ", ', &).
Example: The below example uses the replace() method to escape characters in XML.
function escapeFn(xmlData) {
return xmlData.replace(/[<>"'&]/g, function (char) {
switch (char) {
case '<':
return '<';
case '>':
return '>';
case '"':
return '"';
case '\'':
return ''';
case '&':
return '&';
}
});
}
const xmlData = `
<article>
<title>XML Tutorial</title>
<author>w3wiki</author>
<body>
Hi Beginner!
</body>
</article>
`;
const res = escapeFn(xmlData);
console.log(res);
Output
<article> <title>XML Tutorial</title> <author>w3wiki</author> <body> Hi Beginner! </body> </article>
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 (<, >, &, ") 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.
const xmlEscape = require('xml-escape');
const xmlInput = `
<article>
<title>XML Tutorial</title>
<author>w3wiki</author>
<body>
Hi Beginner!
</body>
</article>
`;
const res = xmlEscape(xmlInput);
console.log(res);
Output:
<article>
<title>XML Tutorial</title>
<author>w3wiki</author>
<body>
Hi Beginner!
</body>
</article>