Kirk Evans Blog

.NET From a Markup Perspective

Getting XML from Somewhere Else

I see this type of question often. 

I want to get XML from another URL.  In MSXML, I used the ServerXMLHTTP component.  How do I do this in .NET?

The simple answer is that the XmlTextReader allows you to specify a URL in its constructor:

public XmlTextReader(string url);

However, sometimes you need a little more control over how you get to the external resource. For instance, you might need to supply custom credentials, add special headers to the HTTP request, or otherwise manipulate the data being sent in the request body. You are provided this control through the System.Net.HttpWebRequest class.  Here is an example of using the HttpWebRequest to form a request and using the response stream to construct an XmlTextReader.

System.Net.HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(“http://localhost/exampleweb/webform1.aspx?id=1″);
webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Accept = “text/xml”;
System.Net.HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
System.IO.Stream responseStream = webResponse.GetResponseStream();
System.Xml.XmlTextReader reader = new XmlTextReader(responseStream);
//Do something meaningful with the reader here