【问题标题】:How to reset if Null? XML Linq如果为 Null,如何重置? XML 链接
【发布时间】:2011-08-21 06:49:04
【问题描述】:

如果结果为空,我目前有以下显示消息框。显示。但它仍然给了我一个未处理的异常。

如何停止异常并让用户输入不同的值?

void Trademe_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;
            if (e.Error == null)


                MessageBox.Show("Wrong try Again");

            var r = XDocument.Parse(e.Result);

为了清晰起见,完整代码************ *****

namespace TradeMe
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            WebClient Trademe = new WebClient();
            Trademe.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Trademe_DownloadStringCompleted);
            Trademe.DownloadStringAsync(new Uri("http://api.trademe.co.nz/v1/Search/General.xml?search_string=" + TradeSearch.Text));

            progressBar1.IsIndeterminate = true;
            progressBar1.Visibility = Visibility.Visible;


        }



        void Trademe_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;






            var r = XDocument.Parse(e.Result);
            if (e.Result == null)
                MessageBox.Show("Wrong try Again");


            // Declare the namespace
            XNamespace ns = "http://api.trademe.co.nz/v1";
            listBox1.ItemsSource = from TM in r.Root.Descendants(ns + "Listing").Take(50)
                                   select new TradeItem
                                   {
                                       ImageSource = TM.Element(ns + "PictureHref").Value,
                                       Title = TM.Element(ns + "Title").Value,
                                       Region = TM.Element(ns + "Region").Value,
                                       PriceDisplay = TM.Element(ns + "PriceDisplay").Value,
                                       ListingId = TM.Element(ns + "ListingId").Value,
                                   };

           ;

            progressBar1.IsIndeterminate = false;
            progressBar1.Visibility = Visibility.Collapsed;
        }



        public class TradeItem
        {
            public string Region { get; set; }
            public string ListingId { get; set; }
            public string PriceDisplay { get; set; }
            public string Title { get; set; }
            public string ImageSource { get; set; }
        }

        private void hyperlinkButton1_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/TestPage.xaml", UriKind.Relative));
        }

        private void eventhandler(object sender, SelectionChangedEventArgs e)
        {
            var item = (sender as ListBox).SelectedItem as TradeItem;

            if (item != null)
            {
                string id = item.ListingId.ToString();
                NavigationService.Navigate(new Uri("/TestPage.xaml?ListingId=" + id, UriKind.Relative));
            }


        }


    }
}

完整的堆栈跟踪 ************* *

   at TradeMe.MainPage.<>c__DisplayClass2.<Trademe_DownloadStringCompleted>b__1(XElement TM)
   at System.Linq.Enumerable.<SelectIterator>d__d`2.MoveNext()
   at System.Windows.Controls.ItemCollection.EnumerableCollectionView.InitializeSnapshot()
   at System.Windows.Controls.ItemCollection.EnumerableCollectionView..ctor(IEnumerable sourceCollection, ICollectionChangedListener collectionOwner)
   at System.Windows.Controls.ItemCollection.UpdateItemsSourceList(IEnumerable newItemsSource)
   at System.Windows.Controls.ItemsControl.ItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.RaisePropertyChangeNotifications(DependencyProperty dp, Object oldValue, Object newValue)
   at System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, ValueOperation operation)
   at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean allowReadOnlySet)
   at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value)
   at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
   at System.Windows.Controls.ItemsControl.set_ItemsSource(IEnumerable value)
   at TradeMe.MainPage.Trademe_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
   at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
   at System.Net.WebClient.DownloadStringOperationCompleted(Object arg)
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at System.Delegate.DynamicInvokeOne(Object[] args)
   at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
   at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
   at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
   at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
   at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)

【问题讨论】:

    标签: xml silverlight linq windows-phone-7


    【解决方案1】:

    您正在检查e.Error 是否为空,而不是e.Result 是否为空...并且在显示消息框后您也没有返回。

    (很难确切地知道发生了什么 - 如果你能说出你得到了什么异常以及在什么情况下,那将是有用的......)

    编辑:好的,从堆栈跟踪来看,它看起来像是在迭代器的选择部分。我强烈怀疑其中一条线路失败了:

    ImageSource = TM.Element(ns + "PictureHref").Value,
    Title = TM.Element(ns + "Title").Value,
    Region = TM.Element(ns + "Region").Value,
    PriceDisplay = TM.Element(ns + "PriceDisplay").Value,
    ListingId = TM.Element(ns + "ListingId").Value,
    

    我的猜测是您要查找的元素之一丢失了。

    如果您将其更改为以下代码,它不会引发异常 - 但之前会引发异常的任何属性都将为 null。这可能是您想要的,但即使不是,它也至少可以帮助您找到问题:

    ImageSource = (string) TM.Element(ns + "PictureHref"),
    Title = (string) TM.Element(ns + "Title"),
    Region = (string) TM.Element(ns + "Region"),
    PriceDisplay = (string) TM.Element(ns + "PriceDisplay"),
    ListingId = (string) TM.Element(ns + "ListingId"),
    

    如果元素为空,则从XElementstring 的显式转换将返回空,例如

    XElement element = null;
    string value = (string) element;
    // value will be null; no exception is thrown
    

    【讨论】:

    • 当用户输入某些值进行搜索时出现未处理的异常错误。我已经更新了完整的代码。为了更清楚地说明我在做什么。
    • @Rhys:“未处理的异常错误”仍然不是很精确。请发布完整的堆栈跟踪并标记任何相关的行号。例如,您可能正在设法很好地解析 XML,但它不包含您期望的元素。
    • 已添加完整的堆栈跟踪。谢谢
    • 无论如何它是否可以忽略它找不到的元素?我认为这可能是问题所在,因为 XML 元素会根据搜索值而变化
    • @Rhys:对,听起来有些元素不存在。请参阅我的编辑。是的,我给出的代码很可能正是你想要的。
    【解决方案2】:

    根据 .NET 4.0 MSDN 文档,您应该按如下方式处理回调:

    private static void DownloadStringCallback2 (Object sender, DownloadStringCompletedEventArgs e)
    {
        // If the request was not canceled and did not throw
        // an exception, display the resource.
        if (!e.Cancelled && e.Error == null)
        {
            string textString = (string)e.Result;
    
            Console.WriteLine (textString);
        }
    }
    

    我认为你必须为 WP7 做类似的事情。因此检查 Canceled 是否为 false 并且 e.Error 是否为空。然后得到结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2011-07-05
      • 1970-01-01
      相关资源
      最近更新 更多