答案是C#中处理xml保留字符需转义,5个预定义实体为<、>、&、”、’,使用XElement等类时自动转义,如new XElement(“Message”, “5 < 10 && x > 0”)会自动输出实体引用,手动场景可用SecurityElement.Escape并补充单引号转义。

在C#中处理XML时,遇到保留字符必须进行转义,否则会导致XML格式错误或解析失败。XML定义了5个预定义实体用于转义特殊字符,C#在使用 XmlDocument、XElement 或 XmlWriter 等类时会自动处理这些字符,但了解底层机制和手动处理方式仍然很重要。
XML中的保留字符及对应实体
以下是XML中需要转义的5个保留字符及其对应的实体引用:
- < →
- > → >
- & → &
- “ → “
- ‘ → ‘
这些字符在XML标签内容或属性值中出现时可能引起解析问题,尤其是 < 和 &。
C#中自动转义的处理方式
使用 .net 提供的 XML 处理类时,大多数情况下不需要手动转义,系统会自动完成。
例如,使用 XElement 添加包含特殊字符的文本:
var element = new XElement("Message", "5 < 10 && x > 0"); Console.WriteLine(element); // 输出: <Message>5 < 10 && x > 0</Message>
可以看到,< 和 & 被自动转义为 和 &。
同样,在设置属性值时:
var root = new XElement("Root", new XAttribute("condition", "name == "test"")); Console.WriteLine(root); // 输出: <Root condition="name == "test"" />
双引号被自动转义为 “。
手动转义与反向解析场景
虽然大多数情况无需手动操作,但在某些场景下(如拼接原始XML字符串或处理用户输入)可能需要手动转义。
可以编写辅助方法进行转义和反转义:
public static string EscapeXml(string input) { if (string.IsNullOrEmpty(input)) return input; return System.Security.SecurityElement.Escape(input) .Replace("'", "'"); }
SecurityElement.Escape 可处理 <、>、& 和 ,但不处理单引号,因此需额外替换。
若需从转义字符串还原原始内容:
public static string UnescapeXml(string input) { if (string.IsNullOrEmpty(input)) return input; return System.Net.WebUtility.HtmlDecode(input); }
HtmlDecode 可正确解析标准XML实体。
注意事项与最佳实践
避免直接拼接XML字符串,容易出错且难以维护。应优先使用 XElement、XmlDocument 或 XmlWriter 等类型安全的方式。
如果必须生成原始XML文本,确保所有动态内容都经过转义处理。
对于CDATA节中的内容,不需要转义:
var cdataElement = new XElement("Script", new XCData("if (a < b && c > d) { }")); Console.WriteLine(cdataElement); // 输出: <Script><![CDATA[if (a < b && c > d) { }]]></Script>
CDATA内的内容会被原样保留,适合包含大量特殊字符的脚本或代码片段。
基本上就这些。只要使用正确的API,C#能帮你处理好大部分转义问题,关键是要理解何时需要干预,何时可以交给框架处理。


