๐ŸŒ
My Tec Bits
mytecbits.com โ€บ tools โ€บ encoders โ€บ xml-encoder
XML Encoder Tool | My Tec Bits.
July 23, 2021 - XML Encoder Tool a free online tool to encode your text having XML's 5 predefined enteties to corresponding escape characters.
๐ŸŒ
Online XML Tools
onlinexmltools.com โ€บ url-encode-xml
URL-encode XML - Online XML Tools
Simple, free and easy to use online tool that URL-encodes XML. No ads, popups or nonsense, just an XML URL-encoder. Load XML, get URL-escaped XML.
๐ŸŒ
Online-domain-tools
xml-encoding.online-domain-tools.com
XML Encoding โ€“ Easily encode or decode strings or files online
Online Encoders and Decoders consists of several tools that allow you to encode or decode data using various methods. Our implementation supports both the text string input and the file input. If the data you want to encode or decode are in the form of a short string we recommend using the text string input.
๐ŸŒ
Zickty
zickty.com โ€บ xmlencode
XML Encode Online Tool
A tool for encoding plain text to XML.
๐ŸŒ
Zickty
zickty.com โ€บ xmldecode
XML Decode Online Tool
A tool for decoding XML to plain text.
๐ŸŒ
URL Encode
urlencoder.org โ€บ enc โ€บ xml
URL Encoding of "xml" - Online
Encode xml to URL-encoded format with various advanced options. Our site has an easy to use online tool to convert your data.
๐ŸŒ
Browserling
browserling.com โ€บ tools โ€บ xml-to-base64
XML to Base64 Converter - Encode XML to Base64 - Online - Browserling Web Developer Tools
Useful, free online tool that converts XML to base64. No ads, nonsense or garbage, just an XML base64 encoder. Press button, get result.
Find elsewhere
๐ŸŒ
Online XML Tools
onlinexmltools.com โ€บ convert-xml-to-base64
Convert XML to Base64 - Online XML Tools
Free online XML to Base64 converter. Just load your XML and it will automatically get encoded to Base64. There are no ads, popups or nonsense, just an awesome XML to Base64 encoder. Load XML, get Base64.
๐ŸŒ
Code Beautify
codebeautify.org โ€บ xml-url-encoding
XML URL Encoding to url encode XML
This tool allows loading the Encoded XML URL, which loads Plain XML strings and converts to XML URL Decoded text.
๐ŸŒ
DocsAllOver
docsallover.com โ€บ tools โ€บ xml-encoder-decoder
DocsAllOver | XML Encoder/Decoder
Easily convert data to and from XML format with DocsAllOver's free online XML encoder/decoder. Convert complex data structures into XML and vice versa. Perfect for developers, data analysts, and anyone working with XML data.
๐ŸŒ
Online XML Tools
onlinexmltools.com โ€บ url-decode-xml
URL-decode XML - Online XML Tools
Simple, free and easy to use online tool that URL-decodes XML. No ads, popups or nonsense, just an XML URL-unescaper. Load URL-encoded XML, get URL-decoded XML.
๐ŸŒ
My Tec Bits
mytecbits.com โ€บ tools โ€บ encoders โ€บ xml-decoder
XML Decoder Tool | My Tec Bits.
July 23, 2021 - XML Decoder Tool is a free online tool to decode your already encoded text having escape codes for XML's 5 predefined enteties.
๐ŸŒ
URL Decode
urldecoder.org โ€บ dec โ€บ xml
URL Decoding of "xml" - Online
Decode xml from URL-encoded format with various advanced options. Our site has an easy to use online tool to convert your data.
๐ŸŒ
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.
Top answer
1 of 13
80

Depending on how much you know about the input, you may have to take into account that not all Unicode characters are valid XML characters.

Both Server.HtmlEncode and System.Security.SecurityElement.Escape seem to ignore illegal XML characters, while System.XML.XmlWriter.WriteString throws an ArgumentException when it encounters illegal characters (unless you disable that check in which case it ignores them). An overview of library functions is available here.

Edit 2011/8/14: seeing that at least a few people have consulted this answer in the last couple years, I decided to completely rewrite the original code, which had numerous issues, including horribly mishandling UTF-16.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

/// <summary>
/// Encodes data so that it can be safely embedded as text in XML documents.
/// </summary>
public class XmlTextEncoder : TextReader {
    public static string Encode(string s) {
        using (var stream = new StringReader(s))
        using (var encoder = new XmlTextEncoder(stream)) {
            return encoder.ReadToEnd();
        }
    }

    /// <param name="source">The data to be encoded in UTF-16 format.</param>
    /// <param name="filterIllegalChars">It is illegal to encode certain
    /// characters in XML. If true, silently omit these characters from the
    /// output; if false, throw an error when encountered.</param>
    public XmlTextEncoder(TextReader source, bool filterIllegalChars=true) {
        _source = source;
        _filterIllegalChars = filterIllegalChars;
    }

    readonly Queue<char> _buf = new Queue<char>();
    readonly bool _filterIllegalChars;
    readonly TextReader _source;

    public override int Peek() {
        PopulateBuffer();
        if (_buf.Count == 0) return -1;
        return _buf.Peek();
    }

    public override int Read() {
        PopulateBuffer();
        if (_buf.Count == 0) return -1;
        return _buf.Dequeue();
    }

    void PopulateBuffer() {
        const int endSentinel = -1;
        while (_buf.Count == 0 && _source.Peek() != endSentinel) {
            // Strings in .NET are assumed to be UTF-16 encoded [1].
            var c = (char) _source.Read();
            if (Entities.ContainsKey(c)) {
                // Encode all entities defined in the XML spec [2].
                foreach (var i in Entities[c]) _buf.Enqueue(i);
            } else if (!(0x0 <= c && c <= 0x8) &&
                       !new[] { 0xB, 0xC }.Contains(c) &&
                       !(0xE <= c && c <= 0x1F) &&
                       !(0x7F <= c && c <= 0x84) &&
                       !(0x86 <= c && c <= 0x9F) &&
                       !(0xD800 <= c && c <= 0xDFFF) &&
                       !new[] { 0xFFFE, 0xFFFF }.Contains(c)) {
                // Allow if the Unicode codepoint is legal in XML [3].
                _buf.Enqueue(c);
            } else if (char.IsHighSurrogate(c) &&
                       _source.Peek() != endSentinel &&
                       char.IsLowSurrogate((char) _source.Peek())) {
                // Allow well-formed surrogate pairs [1].
                _buf.Enqueue(c);
                _buf.Enqueue((char) _source.Read());
            } else if (!_filterIllegalChars) {
                // Note that we cannot encode illegal characters as entity
                // references due to the "Legal Character" constraint of
                // XML [4]. Nor are they allowed in CDATA sections [5].
                throw new ArgumentException(
                    String.Format("Illegal character: '{0:X}'", (int) c));
            }
        }
    }

    static readonly Dictionary<char,string> Entities =
        new Dictionary<char,string> {
            { '"', "&quot;" }, { '&', "&amp;"}, { '\'', "&apos;" },
            { '<', "&lt;" }, { '>', "&gt;" },
        };

    // References:
    // [1] http://en.wikipedia.org/wiki/UTF-16/UCS-2
    // [2] http://www.w3.org/TR/xml11/#sec-predefined-ent
    // [3] http://www.w3.org/TR/xml11/#charsets
    // [4] http://www.w3.org/TR/xml11/#sec-references
    // [5] http://www.w3.org/TR/xml11/#sec-cdata-sect
}

Unit tests and full code can be found here.

2 of 13
35

SecurityElement.Escape

documented here

๐ŸŒ
Online String Tools
onlinestringtools.com โ€บ convert-xml-to-string
Convert XML to a String โ€“ Online String Tools
Free online XML to string converter. Just load your XML and it will automatically get converted to a string. There are no intrusive ads, popups or nonsense, just an XML string extractor. Load XML, get a string.