HTML escaping and XML are closely related. as you said, HttpUtility has HtmlEncode and HtmlDecode . They will also work with XML, as there are only a few objects that need escaping: < , > , \ , ' and & in HTML and XML.
The disadvantage of using the HttpUtility class is that you need a reference to the System.Web dll, which also contains many other things that you probably don't need.
In particular, for XML, the SecurityElement class has an Escape that will encode but does not have a corresponding Unescape method. Therefore, you have several options:
- use
HttpUtility.HtmlDecode() and put the link with the System.Web link scan your own decoding method, which will take care of special characters (since there are only a few - look at the static SecurityElement constructor in Reflector to see the full list)
use a (hacker) solution, for example:
.
public static string Unescape(string text) { XmlDocument doc = new XmlDocument(); string xml = string.Format("<dummy>{0}</dummy>", text); doc.LoadXml(xml); return doc.DocumentElement.InnerText; }
Personally, I would use HttpUtility.HtmlDecode() if I already had a link to System.Web , or roll my own if not. I don't like your XmlReader approach, as it is Disposable , which usually indicates that it uses resources that need to be removed, and therefore can be an expensive operation.
adrianbanks Mar 14 2018-11-11T00: 00Z
source share