从XML文件C#中删除非ASCII字符

时间:2017-03-19 17:37:22

标签: c# xml

我正在尝试编写一个程序来删除打开一个包含非ASCII字符的XML文件,并用空格替换这些字符并保存并关闭该文件。

基本上就是这样,只需打开文件即可删除所有非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();

                }
            }


        }


    }
}

先谢谢你们。

1 个答案:

答案 0 :(得分:0)

根据documentation,第一个字符串是输入参数(并且不通过引用传递,因此无论如何都不能更改)。替换的结果是返回值,如下所示:

var result = Regex.Replace(text, @"[^\u0000-\u007F]+", "", RegexOptions.Compiled);
x.Write(result);

请注意RegexOptions.Compiled可能会降低此处的效果。只有在多个字符串上重用相同的正则表达式实例时才有意义。如果在循环之外创建RegEx实例,您仍然可以这样做:

var regex = new Regex(@"[^\u0000-\u007F]+", RegexOptions.Compiled);

using (var sr = new StreamReader(pth_input))
{
    using (var x = new StreamWriter(pth_output))
    {
        while ((lx = sr.ReadLine()) != null)
        {
            var text = sr.ReadToEnd();
            var result = regex.Replace(text, String.Empty);
            x.Write(result);
        }
    }
}