转义和取消转义无效字符

Escape and unescape invalid characters

这应该很容易。我有一个像下面这样转义的字符串:

string originalString = "M&M";
string escapedString = System.Security.SecurityElement.Escape(originalString);//M&M

到目前为止还不错

string unEscapedString = System.Security.SecurityElement.FromString(escapedString).Text;

期待回到 M&M 但得到 "object not set"

假设字符串应该是 xml 格式,所以任何关于我在这种情况下应该做什么的帮助都会有所帮助。

您可以使用System.Net.WebUtility class's static 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;