【问题标题】:Reading an XML File in .NET Core 3.1 with UTF-8 vs UTF-16在 .NET Core 3.1 中使用 UTF-8 与 UTF-16 读取 XML 文件
【发布时间】:2021-07-01 18:46:42
【问题描述】:

我收到以下错误(我在其他 SO 帖子中看到):

There is no Unicode byte order mark. Cannot switch to Unicode.

我在用户交换的其他 SO 帖子上看到:

<?xml version="1.0" encoding="utf-16"?>

到:

<?xml version="1.0" encoding="utf-8"?>

我无法即时更新所有导入的 XML 来切换它,所以我想知道如何以编程方式进行。我有以下代码,其中

    private static string ParseXML(Stream xmlSteam)
    {
        using (var xmlReader = XmlReader.Create(xmlSteam))
        {
            // Errors out here with the unicode exception being caught
            while (xmlReader.Read())

我正在尝试修复它,以便它能够读取和解析 XML。

【问题讨论】:

    标签: .net xml .net-core xmlreader .net-core-3.1


    【解决方案1】:

    如果您的 XML 是用 UTF-8 编码的,但说它是用 UTF-16 编码的,那么它就是坏数据,处理坏数据的最好办法是找出损坏发生的位置并从源头修复它。

    如果您无法从源头修复它,但您确切知道出了什么问题,则将数据读入 MemoryStream 并调整内容,然后再将其传递给 XML 解析器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      • 2015-12-06
      • 1970-01-01
      相关资源
      最近更新 更多