public static string Escape(this string str, EscapeLanguage language) { var sb = new StringBuilder(str.Length); if (language == EscapeLanguage.Xml) { foreach (char cb in str) { switch (cb) { case '"': sb.Append("""); break; case '\'': sb.Append("'"); break; case '<': sb.Append("<"); break; case '>': sb.Append(">"); break; case '&': sb.Append("&"); break; case '\r': sb.Append(" "); break; case '\n': sb.Append(" "); break; case '\t': sb.Append("	"); break; case '|': sb.Append("|"); break; case '/': sb.Append("/"); break; default: sb.Append(cb); break; } } } return(sb.ToString()); }
public static string Unescape(this string str, EscapeLanguage language) { var sb = new StringBuilder(str.Length); if (language == EscapeLanguage.Xml) { for (int i = 0; i < str.Length;) { if (str[i] == '&') { if (++i >= str.Length) { throw new Exception("Invalid XmlString"); } // find ; int endIndex = str.IndexOf(';', i); if (endIndex == -1 || endIndex - i == 0) // same as &; { throw new Exception("Invalid XmlString"); } var stringAttribute = str.Substring(i, endIndex - i); if (stringAttribute[0] == '#') { if (stringAttribute.Length < 2 || //  (char.ToLower(stringAttribute[1]) == 'x' && stringAttribute.Length < 3)) //  { throw new Exception("Invalid XmlString"); } if (char.ToLower(stringAttribute[1]) == 'x') { var hex = stringAttribute.Substring(2).PadLeft(4, '0'); var val = (char)short.Parse(hex, NumberStyles.HexNumber); sb.Append(val); } else { // number var val = (char)short.Parse(stringAttribute.Substring(1)); sb.Append(val); } } else { switch (stringAttribute.ToLower()) { case "quot": sb.Append('"'); break; case "apos": sb.Append('\''); break; case "lt": sb.Append('<'); break; case "gt": sb.Append('>'); break; case "amp": sb.Append('&'); break; } } // parse this attribute i = endIndex + 1; continue; } sb.Append(str[i++]); } } return(sb.ToString()); }