0
我正在嘗試編寫一個程序,用於刪除打開非ASCII字符的XML文件並用空格替換這些字符並保存並關閉該文件。刪除XML文件中的非ASCII字符C#
基本上就是這樣,只要打開文件就可以清除所有非ascii字符並保存/關閉文件。
這裏是我的代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
namespace RemoveSpecial
{
class Program
{
static void Main(string[] args)
{
string pth_input = string.Empty;
string pth_output = string.Empty;
for (int i = 1; i < args.Length; i++)
{
//input one
string p_input = args[0];
pth_input = p_input;
pth_input = pth_input.Replace(@"\", @"\\");
//output
string p_output = args[2];
pth_output = p_output;
pth_output = pth_output.Replace(@"\", @"\\");
}
//s = Regex.Replace(s, @"[^\u0000-\u007F]+", string.Empty);
string lx;
using (StreamReader sr = new StreamReader(pth_input))
{
using (StreamWriter x = new StreamWriter(pth_output))
{
while ((lx = sr.ReadLine()) != null)
{
string text = sr.ReadToEnd();
Regex.Replace(text, @"[^\u0000-\u007F]+", "", RegexOptions.Compiled);
x.Write(text);
} sr.Close();
}
}
}
}
}
在此先感謝球員。
你在你的代碼中,註釋掉了答案 - 用'Regex.Replace(S,@「[^ \ u0000- \ u007F] +「,string.Empty);' –
你當然意識到XML文檔的含義可以改變。它可能也會被破壞,因爲它可能沒有使用UTF-8進行編碼,所以讀取文件爲UTF-8。它也可能變得不完整(與XML無效)。它也可能在每個適用的模式下變得無效。此外,您並未觸摸數字字符實體引用(例如,&#x1f6b2;而不是),但尚不清楚這是否是您的意圖。通常,最好使用XML庫來操作XML文檔。如果你發現你的成功只是偶然發生,你應該考慮這些問題。 –
這可能是因爲US-ASCII符合您的要求而不改變XML文檔的含義,所以將文檔編碼保存爲XML文檔。 –