理想情况下,XML 在您的代码使用它之前已正确转义。如果这超出了您的控制范围,您可以编写正则表达式。除非您完全确定这些值不包含其他转义项,否则请勿使用 String.Replace 方法。
例如,"wow&".Replace("&", "&")
结果是wow&
这显然是不可取的。
Regex.Replace 可以为您提供更多控制来避免这种情况,并且可以编写为仅匹配不属于其他字符的“&”符号,例如<
, 就像是:
string result = Regex.Replace(test, "&(?!(amp|apos|quot|lt|gt);)", "&");
上面的方法有效,但不可否认,它没有涵盖以 & 开头的各种其他字符,例如
而且这个名单还会继续增长。
更灵活的方法是解码 value 属性的内容,然后重新编码。如果你有value="&wow&"
解码过程将返回"&wow&"
然后重新编码它会返回"&wow&"
,这是理想的。要实现这一点,你可以使用这个:
string result = Regex.Replace(test, @"value=\""(.*?)\""", m => "value=\"" +
HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(m.Groups[1].Value)) +
"\"");
var doc = XElement.Parse(result);
请记住,上述正则表达式仅针对 value 属性的内容。如果 XML 结构中的其他区域遇到相同的问题,则可以对其进行调整以匹配它们并以类似的方式替换其内容。
EDIT: updated solution that should handle content between tags as well as anything between double quotes. Be sure to test this thoroughly. Attempting to manipulate XML/HTML tags with regex is not favorable as it can be error prone and over-complicated. Your case is somewhat special since you need to sanitize it first in order to make use of it.
string pattern = "(?<start>>)(?<content>.+?(?<!>))(?<end><)|(?<start>\")(?<content>.+?)(?<end>\")";
string result = Regex.Replace(test, pattern, m =>
m.Groups["start"].Value +
HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(m.Groups["content"].Value)) +
m.Groups["end"].Value);
var doc = XElement.Parse(result);