2 Comments

You should use the function System.Security.SecurityElement.Escape and not the function System.Web.HttpUtility.HtmlEncode to escape special characters in XML if you don’t want the characters like éûÉ to be converted to éûÉ which is permit able but not necessary en can result in long xml fields.

var escapedXml = System.Security.SecurityElement.Escape(@"&<>'""’éûÉغ");
Console.WriteLine(escapedXml);
// Result=&amp;&lt;&gt;&apos;&quot;’éûÉغ

escapedXml = System.Web.HttpUtility.HtmlEncode(@"&<>'""’éûÉغ");
Console.WriteLine(escapedXml);
// Result=&amp;&lt;&gt;'&quot;’&#233;&#251;&#201;غ

To revert the escape process, use:

SecurityElement securityElement = System.Security.SecurityElement.FromString("<test>H&amp;M</test>");
string unescapedText = securityElement.Text;
Console.WriteLine(unescapedText); // Result: H&M

Or

// Data is the un-escaped text that should be inserted in a XML tag.
string data = "H&amp;M";

// A xml tag with the name "test" is used, just for creating the SecurityElement.
var securityElement = new SecurityElement("test", data);

// Generate the un-escaped text.
string unescapedText = securityElement.Text;

// Result: H&M
Console.WriteLine(unescapedText);

Or use the InnerText property of a XmlNode:

// Data is the un-escaped text that should be inserted in a XML tag.
string data = "H&amp;M";
 
XmlDocument document = new XmlDocument();
document.LoadXml(string.Format("<test>{0}</test>", data));
XmlNode node = document.DocumentElement.FirstChild;

// Generate the un-escaped text.
string unescapedText = node.InnerText;

// Result: H&M
Console.WriteLine(unescapedText);

2 Replies to “You should use System.Security.SecurityElement.Escape in C# to escape special characters in XML and not System.Web.HttpUtility.HtmlEncode”

  1. Nice… Thanks for the info. I had confusion around just this.
    Cheers,
    Mahboob

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts