这应该很容易。我有一个转义字符串,如下所示:
string originalString = "M&M";
string escapedString = System.Security.SecurityElement.Escape(originalString);//M&M
到目前为止还不错
string unEscapedString = System.Security.SecurityElement.FromString(escapedString).Text;
期望返回 M&M,但收到“对象未设置”
假设字符串应该是 xml 格式,所以在这种情况下我应该做什么的任何帮助都会有所帮助。
最佳答案
您可以使用System.Net.WebUtility
类的静态 HtmlDecode
方法:
string original = "M&M";
string escaped = System.Security.SecurityElement.Escape(original);
string unescaped = System.Net.WebUtility.HtmlDecode(escaped);
<小时/>
代码无法正常工作的原因是 FromString
方法需要有效的 xml。请参阅文档 here :
Parameters
xml
String
The XML-encoded string from which to create the security element.
如果您在字符串周围添加 xml 标签,则可以使代码示例正常工作:
string unescaped = SecurityElement.FromString($"<x>{escaped}</x>").Text;
关于c# - 转义和取消转义无效字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59296318/