How to get value from XML web service in C #?

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

For consistency, imagine that the web service is located at www.webservice.com and that if you pass it the POST argument fXML = 1, it will return you

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

I would like him to spit out "somevalue".

+4
source share
4 answers

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 inner text contains "somevalue" return xd.SelectSingleNode(xPath).InnerText; 

EDIT: I just realized that you are talking about a web service, not just XML. In your Visual Studio solution, try right-clicking on the links in Solution Explorer and select Add Web Link. A dialog box will appear asking for the URL, you can simply paste it into: " http://www.webservice.com/webservice.asmx ". VS will auto-generate 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); 
+3
source

I think it will be useful to read this first:

Creating and using a web service (in .NET)

This series is about how web services are used in .NET, including the use of XML input (deserialization).

+4
source

You can use something like this:

 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 did not have the opportunity to check this code, but it should work :)

+2
source

It’s also worth adding that if you need to specifically use POST, not SOAP, you can configure the web service to receive POST calls:

Check Page on MSDN: Configuration Settings for XML Web Services Created Using ASP.NET

0
source

Source: https://habr.com/ru/post/1276607/


All Articles