从XmlReader.ReadInnerXml保存XmlDocument时出现OutOfMemoryException

问题描述

我正在使用XmlReader.ReadInnerXml()加载XML文件的一部分并将其另存为XmlDocument。当innerXml部分超过2 GB(估计)时,我遇到了OutOfMemoryException。处理此错误的最佳方法是什么?有没有更好的方法可以从XmlReader创建大型xml?我可以保存内容而不加载到内存中吗?

using (XmlReader xmlRdr = XmlReader.Create(file))
{
  xmlRdr.MovetoContent();
  while (xmlRdr.Read())
  {
    //when read to XmlNodeType.Element and xmlRdr.Name meets certain criteria
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.PreserveWhitespace = true;
    try
    {
       xmlDoc.LoadXml(xmlRdr.ReadInnerXml());
       //get a few data from within the innerXml and eventually use XmlWritter to save the file                                    
    }
    catch(Exception e)
    {
       string content = $"{e.GetType()} {e.Message} {NewLine} {objId}";
       //send content to log file and email
    }
  }
}

解决方法

如评论中所述,可以尝试使用StreamReaderStreamWriter

tutorial可能有帮助