tags:

views:

722

answers:

4

In C#, if I need to open an HTTP connection, download XML and get one value from the result, how would I do that?

For consistency, imagine the webservice is at www.webservice.com and that if you pass it the POST argument fXML=1 it gives you back

<xml><somekey>somevalue</somekey></xml>

I'd like it to spit out "somevalue".

+3  A: 

I think it will be useful to read this first:

Creating and Consuming a Web Service (in .NET)

This is a series of tutorials of how web services are used in .NET, including how XML input is used (deserialization).

Jon Limjap
+2  A: 

You can use something like that:

var client = new WebClient();
var response = client.UploadValues("www.webservice.com", "POST", new NameValueCollection {{"fXML", "1"}});
using (var reader = new StringReader(Encoding.UTF8.GetString(response)))
{
    var xml = XElement.Load(reader);
    var value = xml.Element("somekey").Value;
    Console.WriteLine("Some value: " + value);                
}

Note I didn't have a chance to test this code, but it should work :)

aku
This seems like an awful lot of work and overhead for a Web Service?!
Rob Cooper
Rob, web service is not always a WSDL\SOAP goodness. Sometimes you need to get and parse data from server yourself. One strange thing about this question is a POST method. Usually such simple services use GET.
aku
+1  A: 

I use this code and it works great:

System.Xml.XmlDocument xd = new System.Xml.XmlDocument;
xd.Load("http://www.webservice.com/webservice?fXML=1");
string xPath = "/xml/somekey";
// this node's inner text contains "somevalue"
return xd.SelectSingleNode(xPath).InnerText;


EDIT: I just realized you're talking about a webservice and not just plain XML. In your Visual Studio Solution, try right clicking on References in Solution Explorer and choose "Add a Web Reference". A dialog will appear asking for a URL, you can just paste it in: "http://www.webservice.com/webservice.asmx". VS will autogenerate all the helpers you need. Then you can just call:

com.webservice.www.WebService ws = new com.webservice.www.WebService();
// this assumes your web method takes in the fXML as an integer attribute
return ws.SomeWebMethod(1);
travis
You're passing parameters via GET not POST as author requested
aku
Grab aku's POST info and edit the answer -- I don't have 2k rep yet :)
Michael Pryor
A: 

It may also be worth adding that if you need to specifically use POST rather than SOAP then you can configure the web service to receive POST calls:

Check out the page on MSDN: Configuration Options for XML Web Services Created Using ASP.NET

Rob Cooper