3

xmlファイル(ansi)を開いて、UTF-8に変換して保存しようとしています。

これが私のコードです:

using System;
using System.IO;
using System.Text;
using System.Xml;



class Test
{

public static void Main()
{
    string path = @"C:\test\test.xml";
    string path_new = @"C:\test\test_new.xml";

    try
    {
        XmlTextReader reader = new XmlTextReader(path);        

          XmlWriterSettings settings = new XmlWriterSettings();
                           settings.Encoding = new UTF8Encoding(false);
            using (var writer = XmlWriter.Create(path_new, settings))
            {
                reader.Save(writer);
            }





    }
    catch (Exception e)
    {
        Console.WriteLine("The process failed: {0}", e.ToString());
    }
}

}

「System.Xml.XmlTextReader」に「Save」の定義が含まれておらず、「System.Xml.XmlTextReader」タイプの最初の引数を受け入れる拡張メソッド「Save」が見つからないというエラーが発生します(ディレクティブまたはアセンブリ参照を使用しますか?)

ここで欠けているクラスは何ですか?私のコードは仕事をするのに正しいですか

編集:

さて、ここで私に例外を与えている別のコード:

using System;
using System.IO;
using System.Text;
 using System.Xml;



class Test
{

public static void Main()
{
    string path = @"C:\project\rdsinfo.xml";
    //string path_new = @"C:\project\rdsinfo_new.xml";

    try
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(path);



    }
    catch (Exception e)
    {
        Console.WriteLine("The process failed: {0}", e.ToString());
    }
}
}

それは私に例外、与えられたエンコーディングの無効な文字を与えています。

4

2 に答える 2

4

それは次のように簡単です:

string path = @"C:\test\test.xml";
string path_new = @"C:\test\test_new.xml";

Encoding utf8 = new UTF8Encoding(false);
Encoding ansi = Encoding.GetEncoding(1252);

string xml = File.ReadAllText(path, ansi);

XDocument xmlDoc = XDocument.Parse(xml);

File.WriteAllText(
    path_new,
    @"<?xml version=""1.0"" encoding=""utf-8""?>" + xmlDoc.ToString(),
   utf8
);

ANSIエンコーディング(サンプルでは1252)を、ANSIファイルが含まれているものに変更します 。エンコーディングのリストを参照してください。

于 2013-01-13T10:43:50.993 に答える
1

writerXmlTextWriterのインスタンスを使用して、このXmlをファイルに書き込むことができます。このクラスには、出力ファイルを生成するために使用できるいくつかのメソッドが含まれています(つまりwriter.WriteString())。

参照は次の場所にあります:http: //msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.aspx

この質問への回答を利用することで、より良い方法を見つけることができます: SQLに挿入するためにutf-8XMLドキュメントをutf-16に変換します

于 2013-01-13T08:28:16.307 に答える