如何删除ISO编码的XML文件中存在的损坏字符

时间:2013-02-01 11:02:37

标签: c# xml encoding utf-16 iso-8859-1

当我尝试将带有UTF-16编码的xml文件转换为ISO-8859-1时,我看到像Â这样的破碎字符。

你能否提出一些解决方法来删除破碎的字符?我希望XML采用ISO编码格式。

这是我的代码,

using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.AppSettings.Get("SqlConn")))
{
    sqlConnection.Open();

    using (SqlCommand sqlCommand = new SqlCommand())
    {
        sqlCommand.CommandTimeout = 0;
        sqlCommand.CommandText = commandText;
        sqlCommand.Connection = sqlConnection;

        // the data from database data is UTF encoded
        using (StreamWriter textwriterISO = new StreamWriter(path + "_out.XML", false, Encoding.GetEncoding("ISO-8859-1")))
        {                                  
            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
            Console.WriteLine("Writing results.This could take a very long time.");
            while (sqlDataReader.Read())
            {
                for (int i = 0; i < sqlDataReader.FieldCount; i++)
                {
                    byte[] arr = System.Text.Encoding.GetEncoding(28591).GetBytes(sqlDataReader[i].ToString());
                    string ascii = Encoding.GetEncoding("UTF-8").GetString(arr);
                    textwriter.WriteLine(sqlDataReader.GetName(i),ascii));
                }

                textwriter.Flush();
            }
        }
    }                         
}

1 个答案:

答案 0 :(得分:2)

您的代码滥用StreamWriter类并对数据进行了错误的手动编码。您正在将源UTF-16 DB数据转换为CP28591,将CP28591字节解释为UTF-8,以便将它们转换回UTF-16,然后让StreamWriter将现在格式错误的UTF-16转换为ISO- 8859-1写入文件时。这是完全错误的事情,更不用说所有这些转换所浪费的开销。让StreamWriter直接处理源UTF-16数据库数据的编码,摆脱其他一切,例如:

using (StreamWriter textwriterISO = new StreamWriter(path + "_out.XML", false, Encoding.GetEncoding("ISO-8859-1")))
{                                  
    SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
    Console.WriteLine("Writing results.This could take a very long time.");
    while (sqlDataReader.Read())
    {
        for (int i = 0; i < sqlDataReader.FieldCount; i++)
        {
            // you were originally calling the WriteLine(String, Object) overload.
            // Are you sure you want to call that? It interprets the first parameter
            // as a pattern to format the value of the second parameter. A DB column
            // name is not a formatting pattern!
            textwriterISO.WriteLine(sqlDataReader.GetName(i), sqlDataReader[i].ToString());

            // perhaps you meant to write the DB column name and field value separately?
            //
            // textwriterISO.WriteLine(sqlDataReader.GetName(i));
            // textwriterISO.WriteLine(sqlDataReader[i].ToString());
        }
        textwriterISO.Flush();
    }
}

话虽如此,你提到你想要XML格式的输出。 StreamWriter本身不会为您输出XML。请使用XmlSerializerXmlTextWriter类将DataReader数据转换为XML,然后将其写入StreamWriter