Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 329
Pop Catalin Avatar asked Sep 05 '08 09:09

Pop Catalin


1 Answers

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);
      }
    }
  }
}
like image 190
Hirvox Avatar answered Sep 23 '22 12:09

Hirvox