23 September, 2009
2 Comments
1 category
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=&<>'"’éûÉغ escapedXml = System.Web.HttpUtility.HtmlEncode(@"&<>'""’éûÉغ"); Console.WriteLine(escapedXml); // Result=&<>'"’éûÉغ
To revert the escape process, use:
SecurityElement securityElement = System.Security.SecurityElement.FromString("<test>H&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&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&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);
Tags: C#XML - XSLT - XPath
Category: Uncategorized
Nice… Thanks for the info. I had confusion around just this.
Cheers,
Mahboob
Very helpful information, thank you!