使用正则表达式,如何转义 xml 属性值中的特殊字符?
给定以下 xml 作为字符串:
"<node attr=\"<Sample>\"></node>"
我想要得到:
"<node attr=\"<Sample>\"></node>"
System.Security.SecurityElement.Escape 函数将无法工作,因为它尝试转义每个特殊字符(包括标记打开/关闭尖括号)。
最佳答案
string text = "<node attr=\"<Sample>\"></node>";
string pattern = @"(?<=\b\w+\s*=\s*"")<\w+>(?="")";
string result = Regex.Replace(text, pattern, m => SecurityElement.Escape(m.Value));
Console.WriteLine(text);
Console.WriteLine(result);
地点:
?<=
- 积极的回顾
\b
- 从单词边界开始匹配
\w+
- 匹配一个或多个单词字符
\s*
- 匹配零个或多个空白字符
?=
- 积极的前瞻
关于c# - 转义 xml 中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33040267/