Search code examples
c#xmlprogressive-download

How to load XML progressively in C#?


I need to process loaded from ResponseStream on Async callbacks XML progressively.

Reply is have:

  <root>
     <node ...>
        .....
     </node>
     <node />
     ...
  </root>

schema, and i need to have ability process <node>'s before they arrive complete.

Is there normal way to parse it using standard .NET?


Solution

  • System.Xml.XmlTextReader 
    

    "Represents a reader that provides fast, non-cached, forward-only access to XML data."

    http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader.aspx

    Edit: This is a quick hack, but it does demonstrate that the reader is in fact lazy.

     public class XmlTextReaderTest
        {
            public void RunTest()
            {
                var fs = new XmlTextReader(new Fs(@"c:\TestXml.xml"));
                while (fs.Read())
                    File.AppendAllText(@"c:\xLog.txt", "Processing node..." + Environment.NewLine);
            }
        }
    
        public class Fs : FileStream
        {
            public Fs(string path)
                : base(path, FileMode.Open)
            {
    
            }
    
            public override int Read(byte[] array, int offset, int count)
            {
                File.AppendAllText(@"c:\xLog.txt", "Reading from stream..." + Environment.NewLine);
                var ans = base.Read(array, offset, count);
                return ans;
            }
    }