This HOW TO describes one of the various built-in methods .NET provides to use XML returned by a web service.
The simplest way to view the returned data is to get the response stream and put it into a string. This is especially handy for debugging. The following code gets a web page and put the the contents in a string.
public static string GetPageAsString(string address)
{
string result = string.Empty;
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Get the web response
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// Get the stream from response
StreamReader reader = new StreamReader(response.GetResponseStream());
// Read the whole contents and return as a string
result = reader.ReadToEnd();
reader.Dispose();
reader = null;
request = null;
return result;
}
To call this method write this code:
GetPageAsString("http://weather.yahooapis.com/forecastrss?p=ITXX0042&u=f");
Here there is the complete sourcecode.
GetXmlFromWebIntoString.rar (37.00 kb)
Sometimes, some network configurations don't allow to access directly to web services.
One way is download the xml file that xml web services returns and load that in a dataset.
I wrote a small function to download xml file from web services.
It's simple, but it's a good starting point to develop other things.
public bool DownloadXmlFromService()
{
string result = "";
try
{
WebProxy proxy = new WebProxy(" proxy address ", port number );
proxy.Credentials = new NetworkCredential( user id , password, domain );
WebRequest request = WebRequest.Create("http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry?CountryName=Italy");
request.Proxy = proxy;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.Stream stream = response.GetResponseStream();
System.Text.Encoding ec = System.Text.Encoding.GetEncoding("utf-8");
System.IO.StreamReader reader = new System.IO.StreamReader(stream, ec);
char [] chars = new Char[256];
int count = reader.Read(chars, 0, 256);
while(count > 0)
{
string str = new String(chars, 0, 256);
result = result + str;
count = reader.Read(chars, 0, 256);
}
response.Close();
stream.Close();
reader.Close();
result = result.Replace("<","<");
result = result.Replace(">",">");
if (File.Exists("temp.xml"))
{
File.Delete("temp.xml");
}
System.IO.StreamWriter ToFile = new StreamWriter("temp.xml");
ToFile.Write(result);
ToFile.Close();
}
catch(Exception exp)
{
string str = exp.Message;
return false;
}
return true;
}