載入或儲存XML時引發的異常.System.ArgumentException: “”(十六進位值 0x1D)是無效的字元。
產生原因是xml檔案中包含低位非列印字元造成的
處理方法:在產生xml檔案的時候,過濾低位非列印字元
把一個字串中的 低序位 ASCII 字元 替換成 &#x 字元
轉換 ASCII 0 - 8 -> � -
轉換 ASCII 11 - 12 -> -
轉換 ASCII 14 - 31 -> -
return System.Text.RegularExpressions.Regex.Replace(HttpUtility.HtmlEncode(str),@"[\x00-\x08]|[\x0B-\x0C]|[\x0E-\x1F]", "");
/// <summary> /// 把一個字串中的 低序位 ASCII 字元 替換成 字元 /// 轉換 ASCII 0 - 8 -> � - /// 轉換 ASCII 11 - 12 -> - /// 轉換 ASCII 14 - 31 -> - /// </summary> /// <param name="tmp"></param> /// <returns></returns> public static string ReplaceLowOrderASCIICharacters(string tmp) { StringBuilder info = new StringBuilder(); foreach (char cc in tmp) { int ss = (int)cc; if (((ss >= 0) && (ss <= 8)) || ((ss >= 11) && (ss <= 12)) || ((ss >= 14) && (ss <= 32))) info.AppendFormat("{0:X};", ss); else info.Append(cc); } return info.ToString(); } /// <summary> /// 把一個字串中的下列字元替換成 低序位 ASCII 字元 /// 轉換 � - -> ASCII 0 - 8 /// 轉換 - -> ASCII 11 - 12 /// 轉換 - -> ASCII 14 - 31 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string GetLowOrderASCIICharacters(string input) { if (string.IsNullOrEmpty(input)) return string.Empty; int pos, startIndex = 0, len = input.Length; if (len <= 4) return input; StringBuilder result = new StringBuilder(); while ((pos = input.IndexOf("", startIndex)) >= 0) { bool needReplace = false; string rOldV = string.Empty, rNewV = string.Empty; int le = (len - pos < 6) ? len - pos : 6; int p = input.IndexOf(";", pos, le); if (p >= 0) { rOldV = input.Substring(pos, p - pos + 1); // 計算 對應的低位字元 short ss; if (short.TryParse(rOldV.Substring(3, p - pos - 3), System.Globalization.NumberStyles.AllowHexSpecifier, null, out ss)) { if (((ss >= 0) && (ss <= 8)) || ((ss >= 11) && (ss <= 12)) || ((ss >= 14) && (ss <= 32))) { needReplace = true; rNewV = Convert.ToChar(ss).ToString(); } } pos = p + 1; } else pos += le; string part = input.Substring(startIndex, pos - startIndex); if (needReplace) result.Append(part.Replace(rOldV, rNewV)); else result.Append(part); startIndex = pos; } result.Append(input.Substring(startIndex)); return result.ToString(); }