This might be a bit more efficient with the same outcome:

function escapeXml(unsafe) {
    return unsafe.replace(/[<>&'"]/g, function (c) {
        switch (c) {
            case '<': return '&lt;';
            case '>': return '&gt;';
            case '&': return '&amp;';
            case '\'': return '&apos;';
            case '"': return '&quot;';
        }
    });
}
Answer from hgoebl on Stack Overflow
🌐
dracoblue.net
dracoblue.net › dev › encodedecode-special-xml-characters-in-javascript
Encode/Decode special xml characters in Javascript / Articles / dracoblue.net
December 23, 2009 - var xml_special_to_escaped_one_map = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' }; var escaped_one_to_xml_special_map = { '&amp;': '&', '&quot;': '"', '&lt;': '<', '&gt;': '>' }; function encodeXml(string) { return string.replace(/([\&"<>])/g, function(str, item) { return xml_special_to_escaped_one_map[item]; }); }; function decodeXml(string) { return string.replace(/(&quot;|&lt;|&gt;|&amp;)/g, function(str, item) { return escaped_one_to_xml_special_map[item]; }); } In JavaScript, Mootools by DracoBlue ·
🌐
Geeksww
geeksww.com › tutorials › web_development › javascript › tips_and_tricks › encoding_values_xml_strings_ajax_web2.php
Javascript: Encoding Values in XML Strings for AJAX / Web 2.0 | Geeks Worldwide
So, now let's say you want to create an XML string manually (in JavaScript) you'll use the function as follows: var xml = "<?xml version='1.0' standalone='yes'?>"; name_variable = trim(document.getElementById('your_name').value); xml += "<name>"; xml += xml_encode(name_variable); xml += "</name>";
🌐
GitHub
gist.github.com › mootoh › 5131361
XML escape function in Javascript. · GitHub
XML escape function in Javascript. Raw · xml_encode.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
GitHub
gist.github.com › panzi › 1857360
Escape XML in JavaScript. · GitHub
April 15, 2016 - DECLARE @x as XML SET @x = (SELECT CAST('<x>' + 'Hello World äöü ÄÖÜäöüàéèâêû'áéóñ' + '</x>' AS xml))
🌐
npm
npmjs.com › package › xml-escape
xml-escape - npm
March 14, 2016 - Escape XML . Latest version: 1.1.0, last published: 10 years ago. Start using xml-escape in your project by running `npm i xml-escape`. There are 148 other projects in the npm registry using xml-escape.
      » npm install xml-escape
    
Published   Mar 14, 2016
Version   1.1.0
Author   Michael Hernandez - michael.hernandez1988@gmail.com
🌐
GitHub
github.com › fb55 › entities
GitHub - fb55/entities: encode & decode HTML & XML entities with ease & speed · GitHub
If your target supports UTF-8, the escapeUTF8 method is going to be your best choice. Otherwise, use either encodeHTML or encodeXML based on whether you're dealing with an HTML or an XML document.
Starred by 377 users
Forked by 73 users
Languages   TypeScript 98.6% | JavaScript 1.4%
Find elsewhere
🌐
W3Schools
w3schools.com › xml › prop_document_inputencoding.asp
XML DOM inputEncoding Property
XML encoding: UTF-8 XML standalone: false XML version: 1.0 Encoding when parsing: UTF-8 Try it Yourself » · The inputEncoding property returns the encoding used for the document (when parsing). ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
MojoAuth
mojoauth.com › escaping › xml-escaping-in-javascript-in-browser
XML Escaping in JavaScript in Browser | Escaping Methods in Programming Languages
XML escaping is the process of converting these special characters into a format that can be safely included in XML documents. This guide explores XML escaping in JavaScript within a browser context, highlighting implementation techniques, best practices, and real-world examples.
🌐
GitHub
gist.github.com › mikedeboer › 1aa7cd2bbcb8e0abc16a
encode/ decode XML entities · GitHub
encode/ decode XML entities · Raw · entities.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Top answer
1 of 3
5

The correct answer is to double encode the text. First with JavascriptEncode and next with XmlAttributeEncode. The rationale behind this is that everything within a xml/html attribute should be XML attribute encoded. The parser of the browser will interpret this as an xml attribute and decode it that way. The browser will supply this decoded text to the javascript interpreter and it should therefore be JavaScript encoded properly to prevent a security leak.

This double encoding will not result invalid results, because the browser will also double decode this text (because two separate interpreters are involved). Here is an example of the correct encoding.

string unsafeText = "Hello <unsafe> ');alert('xss');alert('";
string javaEncoded = AntiXss.JavascriptEncode(unsafeText, false);
ENCODED_STRING = AntiXss.XmlAttributeEncode(javaEncoded);

<input type="button" onclick="alert('[ENCODED_STRING]');"
    value="Click me" />

While double encoding is the only correct way to do this, I like to note that using only JavaScript encoding will usually yield correct result. The constraint here is that the attribute's text is put between quotes.

JavaScript encoding uses the same white list (except for the space character) as HTML/XML attribute encoding. Difference between them is how unsafe characters are encoded. Javascript encodes them as \xXX and \uXXXX (such as \u01A3), while XML attribute encodes them as &#XX; and &#XXXX; (such as &#01A3;). When encoding text with JavaScript encoding, there are only two characters left that will be encoded again by the XML attribute encoder, namely the space character and the backslash character. Those two characters would only be form a problem when the attribute’s text isn’t wrapped between quotes.

Note however that only using XML attribute encoding in this scenario will NOT yield correct result.

2 of 3
2

Install the onclick handler in a separate <script> tag.

<input type="button" id="clickMeButton" value="Click me" />

...

<script type="text/javascript">
...
document.getElementById('clickMeButton').onclick = function () {
   alert([ENCODED STRING HERE using AntiXss.JavascriptEncode]);
}
...
</script>
🌐
CopyProgramming
copyprogramming.com › howto › javascript-encoding-for-xml
JavaScript XML Encoding: Complete Guide with 2026 Best Practices - Javascript xml encoding complete guide
November 30, 2025 - XML encoding in JavaScript is the process of converting special characters and data into a safe format that prevents XML parsing errors and security vulnerabilities. When building web applications or backend services that handle XML data, properly encoding characters like ampersands (&), angle ...
🌐
Compile7
compile7.org › binary-encoding-decoding › how-to-encode-and-decode-using-basexml-in-javascript-in-browser
How to encode and decode using BaseXML in JavaScript in Browser - Compile7
November 26, 2025 - To convert a BaseXML (Base64) encoded string back into its original form, you'll use the atob() function, readily available in the browser's global scope. This built-in JavaScript method takes a Base64 encoded string and returns the original ...
🌐
Code Beautify
codebeautify.org › xml-url-decoding
XML URL Decoding to url decode XML
XML URL Decoding is easy to use tool to Decode XML data which are encoded with URL encoding. Copy, Paste, and Decode. It helps to decode your XML data to Plain XML. It uses the decodeURIComponent method of JavaScript to decode the data.
🌐
SSOJet
ssojet.com › escaping › xml-escaping-in-nodejs
XML Escaping in NodeJS | Escaping Techniques in Programming
This guide dives into effective XML escaping techniques within your Node.js applications. You'll learn how to properly encode characters like <, >, &, ', and " to ensure your XML is well-formed and secure, preventing common parsing errors and protecting against injection attacks.