Pop Catalin Pop Catalin - 2 months ago 17
C# Question

How to do streaming read of a large XML file in C# 3.5

How can you do a streaming read on a large XML file that contains a xs:sequence just below root element, without loading the whole file into a XDocument instance in memory?

Answer

Going with a SAX-style element parser and the XmlTextReader class created with XmlReader.Create would be a good idea, yes. Here's a slightly-modified code example from CodeGuru:

void ParseURL(string strUrl)
{
  try
  {
    using (var reader = XmlReader.Create(strUrl))
    {
      while (reader.Read())
      {
        switch (reader.NodeType)
        {
          case XmlNodeType.Element:
            var attributes = new Hashtable();
            var strURI = reader.NamespaceURI;
            var strName = reader.Name;
            if (reader.HasAttributes)
            {
              for (int i = 0; i < reader.AttributeCount; i++)
              {
                reader.MoveToAttribute(i);
                attributes.Add(reader.Name,reader.Value);
              }
            }
            StartElement(strURI,strName,strName,attributes);
            break;
            //
            //you can handle other cases here
            //
            //case XmlNodeType.EndElement:
            // Todo
            //case XmlNodeType.Text:
            // Todo
            default:
            break;
          }
        }
      }
      catch (XmlException e)
      {
        Console.WriteLine("error occured: " + e.Message);
      }
    }
  }
}