我环顾四周,但未能找到仅转义特殊 XML 字符的内置 .Net 方法:
<
, >
, &
, '
和 "
如果它不是标签。
例如,采用以下文本:
Test& <b>bold</b> <i>italic</i> <<Tag index="0" />
我想把它转换成:
Test& <b>bold</b> <i>italic</i> <<Tag index="0" />
请注意,标签没有转义。我基本上需要将此值设置为 InnerXML
的 XmlElement
因此,必须保留这些标签。
我研究过实现自己的解析器并使用 StringBuilder
尽可能多地优化它,但它会变得非常讨厌。
我也知道可接受的标签可以简化事情(仅:br, b, i, u, blink, flash, Tag)。另外,这些标签可以是自闭标签
(e.g. <u />)
或容器标签
(e.g. <u>...</u>)
最佳答案
注意:这可能会被优化。这只是我为你快速敲出的东西。另请注意,我没有对标签本身进行任何验证。它只是在寻找包含在尖括号中的内容。如果在标签中发现尖括号(例如 <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();
}
}
}
关于c# - 有条件地转义特殊的 xml 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13962225/