Share on Facebook
Welcome to MSDN Blogs Sign in | Join | Help

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
reader.Close();
webResponse.Close();
Published Tuesday, June 24, 2003 1:55 PM by kaevans

Comments

# re: Getting XML from Somewhere Else

Tuesday, August 26, 2003 1:36 PM by Chris
How would you post an XML file to the webserver though? =)

# re: Getting XML from Somewhere Else

Wednesday, November 26, 2003 9:11 AM by Dilip Anand
Hi,

I've also used a simillar code, but i talk to a asp file (which is in another machine). I pass some data and get some data. every thing works fine from webserver (i.e. i log on to the web server and run the app). But not from a client ....any idea.....help would be appreciated

# re: Getting XML from Somewhere Else

Wednesday, November 26, 2003 9:54 AM by Kirk Allen Evans
Sorry, Dilip, I would have no clue where to begin... your question really didn't give any specifics as to what is happening or where any problems might be occurring. Your best bet is to try to isolate the problem to as few lines of code as possible and post up to the ASP.NET forums.

http://www.asp.net/Forums/ShowForum.aspx?tabindex=1&ForumID=43

# Binding External XML to a Dropdown List

Thursday, January 29, 2004 12:47 PM by Kirk Allen Evans' XML Blog

# Use LINQ and .NET 3.5 to Convert RSS to JSON

Tuesday, September 04, 2007 1:46 PM by Kirk Allen Evans' Blog

Scott Guthrie posted a great example of how to create a feed reader using LINQ to XML . Today, I see

# MSDN Blog Postings » Use LINQ and .NET 3.5 to Convert RSS to JSON

New Comments to this post are disabled
 
Page view tracker