c# - 转义 xml 中的特殊字符

标签 c# regex xml xpath

使用正则表达式,如何转义 xml 属性值中的特殊字符?

给定以下 xml 作为字符串:

"<node attr=\"<Sample>\"></node>"

我想要得到:

"<node attr=\"&lt;Sample&gt;\"></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/

相关文章:

php - Bash echo-pipe 进入 Mysql shell 失败

xml - 如何使用insertAfter()在XML中的特定元素之后插入元素

c# - 如何使用 Midi 点网类在 C# 中读取打击乐音符值

c# - .NET 中的 "managed"与 "unmanaged"资源是什么意思?

regex - 是否有 "match the following in any order"或 "match any permutation"的正则表达式?

mysql查询和正则表达式问题

php - 使用 PHP 检索 XML 节点的子集

SQL - 在 XML.value() 中使用变量作为整个 XQuery 路径

c# - 通过代码在 C# Visual Studio 中传递命令行参数

c# - 为什么组合框在创建时会加倍其项目?