Connect to XML file at web address for WP7 app

前端 未结 2 1990
感情败类
感情败类 2021-01-28 03:16

I\'ve been trying to learn the ins-and-outs of Windows Phone 7 programming over the past few weeks. I have learned most of the basics but I\'ve been having trouble finding a tut

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-28 04:00

    ScottGu created an app which demonstrates what you need. (Code below is very similar as couldn't find link to source from his example.)

    The app retrieves XML from a web service (in this case from Twitter.)

        private void GetTweets()
        {
            WebClient twtr = new WebClient();
    
            twtr.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitter_DownloadStringCompleted);
            twtr.DownloadStringAsync(new Uri("http://search.twitter.com/search.atom?&q=searchterm"));
        }
    

    It then parses the XML into a collection of object.

        void twitter_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;
    
            XElement xmlTweets = XElement.Parse(e.Result);
    
            var list = new List();
    
            foreach (XElement t in xmlTweets.Elements("{http://www.w3.org/2005/Atom}entry"))
            {
                var userName = t.Element("{http://www.w3.org/2005/Atom}author").Element("{http://www.w3.org/2005/Atom}name").Value.Split(' ')[0];
                var message = t.Element("{http://www.w3.org/2005/Atom}title").Value;
                var imageSource = (from t2 in t.Elements("{http://www.w3.org/2005/Atom}link")
                                   where t2.Attribute("type").Value.Contains("image")
                                   select t2.Attribute("href").Value).First();
    
                list.Add(new TweetViewModel
                        {
                            UserName = userName,
                            Message = message,
                            ImageSource = imageSource
                        });
            }
    
            twitterList.ItemsSource = list;
        }
    
    
    public class TweetViewModel
    {
        public string UserName { get; set; }
        public string Message { get; set; }
        public string ImageSource { get; set; }
    }
    

    This is then bound to a list.

    
        
            
                
                    
                    
                        
                        
                    
                
            
        
    
    

    It was written with the first CTP of the tools/SDK but hopefully it should still be simple enough to get this working.

提交回复
热议问题