XMLReader无效的XML字符异常

时间:2019-04-12 12:29:33

标签: c# xmlreader

我正在解析一个约500MB的大XML文件,它包含一些无效的XML字符0x07,因此您可以想象发生了什么,XMLReader抛出了一个无效的XML字符异常,为了处理此问题,我们将{将{1}}放入Stream中并使用StreamReader,然后使用Regex.Replace将结果写入内存,然后将干净版本流回StreamWriter,现在我想避免这种情况,并且直接从XMLReader跳过这个肮脏的标签,我的问题是是否有办法实现这一点,下面是我尝试执行此操作的代码段,但此行引发了异常 XMLReader

var node = (XElement)XNode.ReadFrom(xr);

XML SAMPLE,无效属性DaylightSaveInfo

        protected override IEnumerable<XElement> StreamReader(Stream stream, string elementName)
    {

        var arrTag = elementName.Split('|').ToList();
        using (var xr = XmlReader.Create(stream, new XmlReaderSettings { CheckCharacters = false }))
        {
            while (xr.Read())
            {
                if (xr.NodeType == XmlNodeType.Element && arrTag.Contains(xr.Name))
                {
                    var node = (XElement)XNode.ReadFrom(xr);
                    node.ReplaceWith(node.Elements().Where(e => e.Name != "DaylightSaveInfo"));
                    yield return node;
                }
            }
            xr.Close();
        }
 }

BEL Character

2 个答案:

答案 0 :(得分:2)

我刚刚看到Jon Skeet为此写了一些东西,所以我不能真正相信他,但是由于他在SO上的地位远胜于我,所以也许我可以写一两点。 :)

首先,我写了一个重写TextReader类的类。 (链接中的一些参考资料。)

https://www.w3.org/TR/xml/#NT-Char

https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/io/textreader.cs

class FilterInvalidXmlReader : System.IO.TextReader
{
  private System.IO.StreamReader _streamReader;

  public System.IO.Stream BaseStream => _streamReader.BaseStream;

  public FilterInvalidXmlReader(System.IO.Stream stream) => _streamReader = new System.IO.StreamReader(stream);

  public override void Close() => _streamReader.Close();

  protected override void Dispose(bool disposing) => _streamReader.Dispose();

  public override int Peek()
  {
    var peek = _streamReader.Peek();

    while (IsInvalid(peek, true))
    {
      _streamReader.Read();

      peek = _streamReader.Peek();
    }

    return peek;
  }

  public override int Read()
  {
    var read = _streamReader.Read();

    while (IsInvalid(read, true))
    {
      read = _streamReader.Read();
    }

    return read;
  }


  public static bool IsInvalid(int c, bool invalidateCompatibilityCharacters)
  {
    if (c == -1)
    {
      return false;
    }

    if (invalidateCompatibilityCharacters && ((c >= 0x7F && c <= 0x84) || (c >= 0x86 && c <= 0x9F) || (c >= 0xFDD0 && c <= 0xFDEF)))
    {
      return true;
    }

    if (c == 0x9 || c == 0xA || c == 0xD || (c >= 0x20 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD))
    {
      return false;
    }

    return true;
  }
}

然后我创建了一个控制台应用程序,并在其中放置了主要内容:

  using (var memoryStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes("<Test><GoodAttribute>a\u0009b</GoodAttribute><BadAttribute>c\u0007d</BadAttribute></Test>")))
  {
    using (var xmlFilteredTextReader = new FilterInvalidXmlReader(memoryStream))
    {
      using (var xr = System.Xml.XmlReader.Create(xmlFilteredTextReader))
      {
        while (xr.Read())
        {
          if (xr.NodeType == System.Xml.XmlNodeType.Element)
          {
            var xe = System.Xml.Linq.XElement.ReadFrom(xr);

            System.Console.WriteLine(xe.ToString());
          }
        }
      }
    }
  }

希望这会有所帮助,或者至少会提供一些起点。

答案 1 :(得分:-2)

以下xml linq代码运行无错误。我在“ NO”后面的xml文件中使用过:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication108
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.CheckCharacters = false;
            XmlReader reader = XmlReader.Create(FILENAME, settings);

            XDocument doc = XDocument.Load(reader);

            Dictionary<string, string> dict = doc.Descendants("attr")
                .GroupBy(x => (string)x.Attribute("name"), y => (string)y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
    }

}