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 Comments

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.