打开XML文件并将其转换为UTF-8
本文关键字:转换 UTF-8 XML 文件 打开 | 更新日期: 2023-09-27 17:52:52
我正在尝试打开一个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'的定义,也没有扩展方法'Save'接受类型为'System.Xml '的第一个参数。可以找到XmlTextReader'(您是否缺少using指令或程序集引用?)
我错过了什么课?我的代码是否正确完成工作
编辑:好了,这里另一个代码给出了异常:
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());
}
}
}
它给了我一个异常,在给定的编码中无效字符。
就是这么简单:
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文件所在的编码-参见编码列表
您可以使用writer
(XmlTextWriter的实例)将此Xml写入文件。该类包含许多可用于生成输出文件(即writer.WriteString()
)的方法。
参考资料可在以下网址找到:http://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.aspx
利用这个问题的答案可以找到一个更好的方法:将utf-8 XML文档转换为utf-16以便插入SQL