如果xmldocument.load(URL)无法加载,如何返回默认值? [英] how to return default values if xmldocument.load(URL) fails to load?

查看:81
本文介绍了如果xmldocument.load(URL)无法加载,如何返回默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我写了一个返回xmlelement的Web服务.代码的相关部分如下...

Hello all, i have written a webservice that returns an xmlelement. The relevant part of the code is as follows...

[WebMethod(Description = "Get Current Weather Condition for a particular city")]
        public XmlElement GetWeatherCondition(string strLocation)
        {

            strLocation += ".xml";
            DataSet ds = new DataSet("Weather_Condition");

            XmlDocument xmlConditions = new XmlDocument();


            try
            {
              xmlConditions.Load(string.Format("http://api.wunderground.com/api/xxxxxxx/geolookup/conditions/q/np/{0}", strLocation));

                if (xmlConditions.SelectSingleNode("/response/error") != null)
                {
                    //condition = null;
                    condition.Error = xmlConditions.SelectSingleNode("/response/error/description").InnerText;

                }
                else
                {
                    condition.City = xmlConditions.SelectSingleNode("/response/location/city").InnerText;
                    condition.Condition = xmlConditions.SelectSingleNode("/response/current_observation/weather").InnerText;

.........
dtCurrent.Rows.Add(condition.City, DateTime.Now.DayOfWeek.ToString(), condition.Condition, condition.TempF, condition.TempC, condition.Humidity, condition.Wind, condition.Error, condition.IconUrl);
                    ds.Tables.Add(dtCurrent);
                }
                
                XmlDataDocument xDataDoc = new XmlDataDocument(ds);
            XmlElement xDataElement = xDataDoc.DocumentElement;

            return xDataElement;
}                            


该代码适用于gr8,但是当没有Internet连接时,则xmlconditions.Load(返回xml数据的url)将失败.现在,我想要的是如果没有互联网连接,那么我想返回位于不同类(条件)内的默认值.我怎样才能做到这一点??我把它写成如下


The Code works gr8, but when there is no internet connection, then the xmlconditions.Load( url that returns the xml data) fails. Now what i want is if there is no internet connection then i want to return default values that''s inside a different class(condition). How can i do that?? i wrote it in catch as follows

catch 
            {
                dtCurrent.Rows.Add(condition.City, DateTime.Now.DayOfWeek.ToString(), condition.Condition, condition.TempF, condition.TempC, condition.Humidity, condition.Wind, condition.Error, condition.IconUrl);
                ds.Tables.Add(dtCurrent);
                
            }

,但这会中断整个应用程序的执行,并且由于此单个天气控件,Webform不会加载.

进一步改进问题...我在一个类库中调用了此函数...在库中,我有如下函数...

but this breaks the execution of the entire application and webform does not load beacause of this single weather control.

Further improving the Question...i have called this function in a classlibrary...in the library i have a function as follows...

public Dictionary<string,string> LoadCurrentCondition(string strCity)
        {
            
            XmlElement xData = Weather.GetWeatherCondition(strCity);
// this function call fails when there is no internet connection...some //webservice.soapexception...



我想在GetWeatherCondtion()函数中进行更改,以便在没有Internet连接时可以返回默认值.

仅供参考,条件类如下,



i want to make changes in the GetWeatherCondtion() function so that it can return default values when there is no internet connection.

FYI, Condtion class is as follows,

public class Conditions
    {
        private string strCity = "No Data";
        private string strConditions = "No Data";
        private string strDayOfWeek = DateTime.Now.DayOfWeek.ToString();
        private string strTempF = "No Data";
        private string strMinTempF = "No Data";
        private string strTempC = "No Data";

 public string City
        {
            get
            {
                return this.strCity;
            }
            set
            {
                this.strCity = value;
            }

        }
        public string Condition
        {
            get
            {
                return this.strConditions;
            }
            set
            {
                this.strConditions = value;
            }
        }
}


从条件类中可以看到,我只需要获取属性值并返回它们...默认情况下,当没有互联网连接时,默认为无数据" ...但是我无法执行此操作如此.
请帮忙
Minghang


as you can see from the conditions class, i just need to get the properties values and return them...which is by default "No DATA" when there is no internet connection...but i''m not being able to do so.
Please help
Minghang

推荐答案

为什么不将XmlDocument.Load放入单独的try catch

Why dont you put your XmlDocument.Load in separate try catch

try
{
xmlConditions.Load(string.Format("http://api.wunderground.com/api/xxxxxxx/geolookup/conditions/q/np/{0}", strLocation));
}
catch()
{
 // prepare dummy XML
}
//Also check if document loaded correctly
if(xmlConditions == null || xmlConditions.DocumentElement == null)
{
 // prepare dummy xml
}



希望有帮助.
OP评论后更新:
明行我相信您正在尝试将整个代码放到尝试中,而您正在准备中的xml.在这种情况下,它可能会在某个地方引发异常,并且在您的捕获中,您只是在准备表和数据集,而不是从中获取XML.

我建议的内容几乎没有什么不同,即只需将XmlConditions.Load放在单独的(内部)尝试中,然后在该尝试中捕获您准备虚拟XML并从那里本身返回.
或者其他方法是将返回XML准备工作放在finally块中.

抱歉,如果您误解了您的要求.
Milind



Hope that helps.
Updated after OP comment:
Minghang. I believe you are trying to put whole code in the try and in the catch you are preparing the xml. In this case, probably it is throwing exception at some place and in your catch you are just preparing the table and datase but not XML out of it.

What I am suggesting is little different i.e. just put XmlConditions.Load in the separate (inner) try and in that try''s catch you prepare dummy XML and return from there itself.
Or other way is to put return XML preparation in the finally block.

Sorry if misunderstood your requirement.
Milind


您可以有一个默认的构造函数,比方说,无参数.您不必编写一个,因为if可以是唯一的和默认的(隐式)构造函数,而实际的默认值由每个成员默认情况下由初始化程序初始化,C#类允许使用,但结构除外.通过序列化(数据协定或其他任何方式)的初始化可以在您类型的工厂方法中完成,将其称为Load.失败的Load可以回退到默认值.对于一个类,它看起来像这样:

You can have a default constructor, let''s say, parameterless. You don''t have to write one, because if can be your only and default (implicit) constructor, and the actual defaults are initialized by each member by default of by initializers, which are allowed in C# classes but not structures. An initialization through serialization (Data Contract or whatever) could be done in a factory method of your type, call it Load. Failed Load can fallback to default. For a class, it would look like this:

[DataContract(/* ... */] // maybe, it's not a point here
public class MyClass {

    public static class MyClass Load(System.IO.Stream stream) { // a factory method
        try {
            return GetInstanceFromSerialization(stream); // whatever it is
        } catch {
            return new MyClass(); // falls back to default
        } //exception
    } //Load

    public static MyClass Load(string filename) { // another factory method
        try {
            return GetInstanceFromSerialization(filename); // whatever it is
        } catch {
            return new MyClass(); // falls back to default
        } //exception
    } //Load

    public MyClass() { /* ... */ } //this constructor may or may not be needed,
    //depending on available per-member initializers and other constructors

    //...

} //class MyClass



就如此容易.只是想法.如果您的情况更为复杂,则想法是相同的.如果您仍对在更复杂的情况下执行此操作感到困惑,请随时询问您的后续问题.

—SA



As simple as that. Just the idea. If your case is somewhat more complex, the idea is the same. If you are still confused about doing it for more complex cases, don''t hesitate to ask your follow-up questions.

—SA


这篇关于如果xmldocument.load(URL)无法加载,如何返回默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆