【问题标题】:Convert existing XML file from ANSI encoding standard to UTF-8 encoding standard in C#在 C# 中将现有 XML 文件从 ANSI 编码标准转换为 UTF-8 编码标准
【发布时间】:2020-11-13 03:07:50
【问题描述】:

我正在尝试将现有 XML 文件转换为 UTF-8,文件中未指定编码,因为它具有度数 (°) 和上标 (²) 等符号,我假设它是 ANSI 编码。因此,我得到了一个例外:

抛出异常:System.Xml.dll 中的“System.Xml.XmlException” System.Xml.dll 中出现“System.Xml.XmlException”类型的异常,但未在用户代码中处理 给定编码中的无效字符。第 5 行,位置 48。

我用来加载文件的代码。

        XmlDocument xmlDocument;
        xmlDocument = new XmlDocument();
        string currentDir = Environment.CurrentDirectory;
        //getting the directory
        DirectoryInfo directory = new DirectoryInfo(
        Path.GetFullPath(Path.Combine(currentDir, @"..\..\" + @"utils\XML\test.xml")));

        //loading the xml file
        xmlDocument.Load(directory.ToString());

所以我的问题是:有没有办法使用 C# 以可编程方式转换编码?

一种方法是将文件作为字符串读取,但这不可行,因为文件应该非常大,因此很难处理。

        string fileContent = File.ReadAllText(directory.ToString());
        xmlDocument.LoadXml(fileContent);

【问题讨论】:

  • 您的 xml 应该在其声明中包含编码。无论如何,您可以通过使用 Load(Stream) overload 并传递 StreamReader(Stream, Encoding) 来指定编码
  • 张贴 xml 的开头,这样我就可以看到真正的错误。错误在第 5 行。 ToString() 可能会导致其他错误。我怀疑如果您使用 XmlReader.Create(filename) 阅读,这将起作用。您可能需要添加 XmlReaderSetting 以忽略某些检查。
  • @jdweng 文件开头没有包含编码。它看起来像这样:<?xml version="1.0" ?>

标签: c# xml encoding utf-8


【解决方案1】:

我无法使用 XmlDocument 或 XDocument 直接更改编码,所以我必须找到另一种方法。我使用 StreamReader 读取 XML 文件内容:

string currentDir = Environment.CurrentDirectory;
StreamReader sr = new StreamReader(Path.GetFullPath(Path.Combine(currentDir, @"..\..\" + @"utils\XML\test.xml")));

然后使用 XmlDocument 将其作为字符串加载

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(sr.ReadToEnd());

之后,我的解决方案是从 XML 中删除第一行并插入一个新声明。

XmlDeclaration xmldecl = xmlDocument.CreateXmlDeclaration("1.0", "utf-8", null);
            xmlDocument.InsertBefore(xmldecl, xmlDocument.FirstChild);
            xmlDocument.Save(Path.Combine(currentDir, @"..\..\" + @"utils\XML\test-1.xml"));

最后要删除无效字符,我只是将文件读入字符串并替换未知字符“�”,因为当它作为字符串读取时,所有无效字符都将替换为该字符(问号框)。这里可以做的是用其他东西替换字符(为了我的代码,我把它留空了)

var fileContent = File.ReadAllText(Path.Combine(currentDir, @"..\..\" + @"utils\XML\test-1.xml"));
            fileContent = Regex.Replace(fileContent, "�", "");
            File.WriteAllText(Path.Combine(currentDir, @"..\..\" + @"utils\XML\test-1.xml"), fileContent);

这是我想出的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    相关资源
    最近更新 更多