次の方法で共有


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("https://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();

Comments

  • Anonymous
    August 26, 2003
    How would you post an XML file to the webserver though? =)

  • Anonymous
    November 26, 2003
    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

  • Anonymous
    November 26, 2003
    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

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

  • Anonymous
    September 04, 2007
    PingBack from http://msdnrss.thecoderblogs.com/2007/09/04/use-linq-and-net-35-to-convert-rss-to-json/