Sep 28 2006

Reading XML from a URL with C#

Posted by admin under XML

This console program will show you a technique to read XML from an Internet sote for example. The XmlTextReader lets you specify http:// as protocol and will then make a webrequest to fetch the data for you.

While the same goes for XmlDocument - the technique of using the XmlTextReader allows for better performance. The XmlDocument loads the whole document into memory - XmlTextReader just works with one single xml element at the time.  So for large documents - use XmlTextReader if possible.

While the example is *kind of dumb* in that sense - reading with XmlTextReader and dumping it all into a StringBuilder - but I chose to show this technique cause it could very well be that you need to do some work on each node or present it in some other way. And still - this technique probably gives you  better performance even with small documents, cause involving a XmlDocument would lead to a lot of extra overhead, not present in the StringBuilder solution.



            string sUrl = "http://www.aspcode.net/articles/rss.ashx";
            StringBuilder oBuilder = new StringBuilder();
            StringWriter oStringWriter = new StringWriter(oBuilder);
            XmlTextReader oXmlReader = new XmlTextReader(sUrl);
            XmlTextWriter oXmlWriter = new XmlTextWriter(oStringWriter);
            while (oXmlReader.Read())
            {
                oXmlWriter.WriteNode(oXmlReader, true);
            }
            oXmlReader.Close();
            oXmlWriter.Close();
            Console.WriteLine( oBuilder.ToString() );


The namespaces needed are:



using System;
using System.Text;
using System.Xml;
using System.IO;