[英]Escape special characters in xml
Using Regex, how can I escape special characters in xml attribute values?使用正则表达式,如何转义 xml 属性值中的特殊字符?
Given the following xml as string:给定以下 xml 作为字符串:
"<node attr=\"<Sample>\"></node>"
I want to get:我想得到:
"<node attr=\"<Sample>\"></node>"
System.Security.SecurityElement.Escape function won't work as it tries to escape every special characters (including tag opening/closing angle brackets). 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);
Where:在哪里:
?<=
- positive lookbehind ?<=
- 正面回顾\\b
- start the match at a word boundary \\b
- 在单词边界处开始匹配\\w+
- match one or more word characters \\w+
- 匹配一个或多个单词字符\\s*
- match zero or more white-space characters \\s*
- 匹配零个或多个空白字符?=
- positive lookahead ?=
- 正向预测
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.