加载或保存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();
- }