tags:

views:

29

answers:

3

There is some php API service that when sent some parameters in query string, it returns date in xml format. So I was wondering how to send call the page and get back the result in c# .net. Like with an xml reader or xml scheme?

+4  A: 

You could pass an url address to XmlReader:

using (var reader = XmlReader.Create("http://example.com/somexml"))
{
    // TODO: parse
}

Another possibility is to use XDocument:

var doc = XDocument.Load("http://example.com/somexml");
// TODO: manipulate the document

And yet another possibility is to use a WebClient:

using (var client = new WebClient())
{
    string xml = client.DownloadString("http://example.com/somexml");
    // TODO: feed the xml to your favorite XML parser
}
Darin Dimitrov
It's not clear to me whether XDocument.Load will *actually* work with a URI. The documentation suggests it's for *files* rather than URIs, although this would be a bit of a departure.
Jon Skeet
@Jon, it works, tested it. Internally the method does exactly what you wrote in your answer with a little addition of a `XmlReaderSettings`.
Darin Dimitrov
@Darin: Cool... and the parameter name is definitely suggestive, which I'd missed too. Oops :)
Jon Skeet
+3  A: 

If the parameters are in the query string, it's pretty easy... I would use XmlReader.Create as per Darin's answer, and then for ease of working with the XML, I'd use LINQ to XML:

XDocument doc;
using (var reader = XmlReader.Create("http://example.com/somexml"))
{
    doc = XDocument.Load(reader);
}
// Now work with doc

(EDIT: As Darin noted, XDocument.Load(string uri) makes this simpler - ignore the fact that the docs say it loads the data from a file.)

If you need more control over the HTTP side of things (e.g. to include post data) you can use something like:

WebRequest request = WebRequest.Create(...);
// Fiddle with request here

XDocument doc;
using (WebResponse response = request.GetResponse())
using (Stream data = response.GetResponseStream())
{
    doc.Load(data);
}
// Use doc here

Note that this is all synchronous - parsing it all asynchronously is possible too, but more work.

Jon Skeet
A: 

A better way is

XmlDocument xdoc;
xdoc = new XmlDocument();
xdoc.Load(XmlReader.Create("weblink"));

The XDocument is not possible to be analyzed and extract its XML values which is possible in XmlDocument

Ahmad Farid