Ami*_*mir 6 c# xml escaping entityreference
我环顾四周了很多,但一直没能找到一个内置的.NET方法只会逃避特殊XML字符:
<,>,&,'和"
如果它不是一个标签.
例如,采用以下文本:
Test& <b>bold</b> <i>italic</i> <<Tag index="0" />
Run Code Online (Sandbox Code Playgroud)
我希望它转换为:
Test& <b>bold</b> <i>italic</i> <<Tag index="0" />
Run Code Online (Sandbox Code Playgroud)
请注意,标签不会被转义.基本上,我需要这个值设置到InnerXML的XmlElement,因此,这些标签必须保留.
我已经研究过实现我自己的解析器并使用a StringBuilder来尽可能地优化它,但它可能变得非常讨厌.
我也知道可以接受的标签可以简化事情(仅限:br,b,i,u,blink,flash,Tag).此外,这些标签可以是自闭标签
(e.g. <u />)
Run Code Online (Sandbox Code Playgroud)
或容器标签
(e.g. <u>...</u>)
Run Code Online (Sandbox Code Playgroud)
注意:这可能可以优化。这只是我快速为你敲出来的东西。另请注意,我没有对标签本身进行任何验证。它只是寻找用尖括号括起来的内容。如果在标签内发现尖括号(例如 <sometag label="I put an > here">),它也会失败。除此之外,我认为它应该满足您的要求。
namespace ConsoleApplication1
{
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
// This is the test string.
const string testString = "Test& <b>bold</b> <i>italic</i> <<Tag index=\"0\" />";
// Do a regular expression search and replace. We're looking for a complete tag (which will be ignored) or
// a character that needs escaping.
string result = Regex.Replace(testString, @"(?'Tag'\<{1}[^\>\<]*[\>]{1})|(?'Ampy'\&[A-Za-z0-9]+;)|(?'Special'[\<\>\""\'\&])", (match) =>
{
// If a special (escapable) character was found, replace it.
if (match.Groups["Special"].Success)
{
switch (match.Groups["Special"].Value)
{
case "<":
return "<";
case ">":
return ">";
case "\"":
return """;
case "\'":
return "'";
case "&":
return "&";
default:
return match.Groups["Special"].Value;
}
}
// Otherwise, just return what was found.
return match.Value;
});
// Show the result.
Console.WriteLine("Test String: " + testString);
Console.WriteLine("Result : " + result);
Console.ReadKey();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1835 次 |
| 最近记录: |