I got the codes below to encode XML content in String. It's working fine to encode a single tag, but not all the tags within.
String a = @"<main>" + "<Title title=\"Hello & <> World\" />" + "<Content content=\"bla bla <tt> bla... by ? & c1% to ??? on other bla bla....\" />" + "</main>"; String b = a.MakeXMLCompatible(); MessageBox.Show(a + "\n\n" + b); static class SubstringExtensions { public static String MakeXMLCompatible(this String value, String tag = "") { String oldStr = value.Between(tag + "=\"", "\" />"); String newStr = System.Security.SecurityElement.Escape(oldStr); if (oldStr == "") { return ""; } Int32 contentAttribContentValueStart = value.IndexOf(tag + "=\"") + (tag + "=\"").Length; Int32 contentAttibContentValueEnd = value.IndexOf("\" />", contentAttribContentValueStart); return String.Concat(value.Substring(0, contentAttribContentValueStart), newStr, value.Substring(contentAttibContentValueEnd)); } public static String Between(this String value, String a, String b, Boolean useLastIndex = false) { int posA = value.IndexOf(a); if (posA == -1) { return ""; } int posB = (useLastIndex ? value.LastIndexOf(b, posA) : value.IndexOf(b, posA)); if (posB == -1) { return ""; } int adjustedPosA = posA + a.Length; if (adjustedPosA >= posB) { return ""; } return value.Substring(adjustedPosA, posB - adjustedPosA); } } How can I enhance the existing codes so that all tags will be encoded?