Skip to main content
 首页 » 编程设计

c#之从 Web 服务读取 XML 或对象

2024年02月06日31sky-heaven

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

谢谢。

我当前的代码

wetther.Weather wether = new wetther.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);   
}   

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

我需要使用这个网络服务 -> http://wsf.cdyne.com/WeatherWS/Weather.asmx

请您参考如下方法:

最好的方法是将对 Web 服务的引用添加到您的项目中。从这里您将能够查询 Web 服务,就像它是您项目中的一个类一样。在 Solution Explorer 中右键单击您的项目,然后单击 Add Service Reference。然后,您可以将网络服务 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),然后您可以检索该对象的属性。