猿问

在C#中转义无效的XML字符

我有一个包含无效XML字符的字符串。在解析字符串之前,如何转义(或删除)无效的XML字符?



ITMISS
浏览 1037回答 3
3回答

函数式编程

这是上述方法RemoveInvalidXmlChars的优化版本,该方法不会在每次调用时都创建一个新数组,因此不必要地给GC施加了压力:public static string RemoveInvalidXmlChars(string text){&nbsp; &nbsp; if (text == null)&nbsp; &nbsp; &nbsp; &nbsp; return text;&nbsp; &nbsp; if (text.Length == 0)&nbsp; &nbsp; &nbsp; &nbsp; return text;&nbsp; &nbsp; // a bit complicated, but avoids memory usage if not necessary&nbsp; &nbsp; StringBuilder result = null;&nbsp; &nbsp; for (int i = 0; i < text.Length; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var ch = text[i];&nbsp; &nbsp; &nbsp; &nbsp; if (XmlConvert.IsXmlChar(ch))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result?.Append(ch);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else if (result == null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = new StringBuilder();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.Append(text.Substring(0, i));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if (result == null)&nbsp; &nbsp; &nbsp; &nbsp; return text; // no invalid xml chars detected - return original text&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; return result.ToString();}
随时随地看视频慕课网APP
我要回答