3

I'm trying to open a xml file (ansi) and converting and saving it UTF-8.

Here is my code:

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());
    }
}

}

I'm getting an error 'System.Xml.XmlTextReader' does not contain a definition for 'Save' and no extension method 'Save' accepting a first argument of type 'System.Xml.XmlTextReader' could be found (are you missing a using directive or an assembly reference?)

What class am I missing here ? Is my code correct to do the job

EDIT:

Okay here another code that is giving me exception:

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());
    }
}
}

It's giving me an exception, invalid character in the given encoding.

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

You can use writer, your instance of XmlTextWriter, to write this Xml to a file. This class contains a number of methods that can be used to generate the output file (i.e. writer.WriteString()).

The reference can be found at: http://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.aspx

A better method can be found by utilizing the answer to this question: Convert utf-8 XML document to utf-16 for inserting into SQL

于 2013-01-13T08:28:16.307 回答