Kirk Evans Blog

.NET From a Markup Perspective

Getting XML from Somewhere Else

Getting XML from Somewhere Else

  • Comments 6

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
reader.Close();
webResponse.Close();
Page 1 of 1 (6 items)
Leave a Comment
  • Please add 2 and 5 and type the answer here:
  • Post
Translate This Page
Search
Archive
Archives