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.

user726720
  • 1,127
  • 7
  • 25
  • 59
  • well the error kinda says it all. XmlTextReader doesn't have a method Save() so you can't just type it and assume the compiler is going to "get" what you mean... – Wim Ombelets Jan 13 '13 at 09:04

2 Answers2

4

It is as simple as:

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

Change the ANSI encoding (1252 in the sample) to whichever one your ANSI file is in - see list of encodings.

Jonathan
  • 6,939
  • 4
  • 44
  • 61
Esailija
  • 138,174
  • 23
  • 272
  • 326
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

Community
  • 1
  • 1
Brett Wolfington
  • 6,587
  • 4
  • 32
  • 51