从Web服务读取XML或对象

本文关键字:对象 XML 读取 Web 服务 | 更新日期: 2023-09-27 18:07:33

这是我第一次使用Web服务,我有点不知所措。我成功地调用了函数,但我只能从中获得一个值服务。我读到最简单的方法是读取xml或创建对象然后调用它们的值。目前我使用的函数返回所需的值,但我需要调用它们3次才能获得所有数据,这是浪费时间和资源。我试着用URL调用该服务,并将其用作网站或者在不导入程序的情况下使服务以相同的方式工作。问题是,我找不到将值传递到url的方法,因为我只看到空白页。从服务中获取数据的最快方法是什么?如果城市有效,我需要城市名称、温度和旗帜。我需要通过拉链服务的代码。

谢谢。

我当前的代码

更湿的天气。Weather((;

        string farenhait = wether.GetCityWeatherByZIP(zip).Temperature;
        string city = wether.GetCityWeatherByZIP(zip).City;
        bool correct = wether.GetCityWeatherByZIP(zip).Success;

我试过了

// Retrieve XML document  
XmlTextReader reader = new XmlTextReader("http://xml.weather.yahoo.com/forecastrss?p=94704");  
// Skip non-significant whitespace  
reader.WhitespaceHandling = WhitespaceHandling.Significant;  
// Read nodes one at a time  
while (reader.Read())  
{  
    // Print out info on node  
    Console.WriteLine("{0}: {1}", reader.NodeType.ToString(), reader.Name);  
}  

这个适用于雅虎页面,但不适用于我的页面。

我需要使用此Web服务->http://wsf.cdyne.com/WeatherWS/Weather.asmx

从Web服务读取XML或对象

最好的方法是在项目中添加对web服务的引用。从这里,您将能够像查询项目中的类一样查询web服务。右键单击Solution Explorer中的项目,然后单击Add Service Reference。然后,您可以将Web服务URL复制并粘贴到对话框中。

然后你可以这样查询。。。

Weather.WeatherSoapClient w = new Weather.WeatherSoapClient();
Weather.ForecastReturn f = w.GetCityForecastByZIP("12345");
string farenhait = f.Temperature;
string city = f.City;
bool correct = f.Success;

基本上,您所做的是每次触发HTTP请求。您需要做的是将单个请求放入一个对象(f(中,然后可以检索其属性。

WeatherServiceRef.WeatherSoapClient weatherSoapClient = new WeatherSoapClient("WeatherSoap");
WeatherServiceRef.ForecastReturn forecastRet = weatherSoapClient.GetCityForecastByZIP("90210"); //enter valid zip string
foreach (Forecast forecast in forecastRet.ForecastResult)    
    {
    Console.WriteLine("'nForecast {0}", forecast.WeatherID);
    Console.WriteLine ("Temperature (morning low): {0}", forecast.Temperatures.MorningLow);
    Console.WriteLine("Temperature (morning high): {0}", forecast.Temperatures.DaytimeHigh);
    Console.WriteLine("Probability of precipitation (daytime): {0}", forecast.ProbabilityOfPrecipiation.Daytime)
    //insert other code to retrieve values here
   }
Console.ReadLine();

您可以使用右键单击添加服务将服务引用添加到web服务。在我的情况下,我已经调用了服务参考WeatherServiceRef。

我使用了@MichaelCoxes awser并找到了这个。完美工作

        degress.TempConvert todegress = new degress.TempConvert();
        wetther.Weather wether = new wetther.Weather();
        wetther.WeatherReturn f = wether.GetCityWeatherByZIP("10001");
        string city = f.City;
        bool correct = f.Success;
        string farenhait = f.Temperature;