本文介绍了从网站将XML文件加载到XDocument(Silverlight和Windows Phone 7)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在Windows Phone 7和Silverlight应用程序中访问的XML文件.XML文件位于Web服务器上,我想通过 http://www.mydomain访问. com/data/this_is_my_file.xml .

I have an XML file that I want to access in an Windows Phone 7 and Silverlight application.Th XML file is on a webserver, and I want to access it through http://www.mydomain.com/data/this_is_my_file.xml.

如何使用此URL将XML文件加载到XDocument中?

How do I use this URL to load the XML file into an XDocument?

推荐答案

您可以使用WebClientHttpWebRequest(异步)下载并解析响应.下面是从Web下载和解析XML的最简单方法之一-

You can use WebClient or HttpWebRequest to download (asynchronously) and parse the response. One of the simplest approach to download and parse XML from the web is below -

public void LoadXmlItems(string xmlUrl)
{
   WebClient client = new WebClient();

   client.OpenReadCompleted += (sender, e) =>
   {
        if (e.Error != null)
            return;

        Stream str = e.Result;
        XDocument xdoc = XDocument.Load(str);

        // take 10 first results
        List<RssFeedItem> rssFeedItems = (from item in xdoc.Descendants("item")
                                            select new XmlItem()
                                            {
                                                Title = item.Element("title").Value,
                                                Description = item.Element("description").Value,
                                                Url = new Uri(item.Element("link").Value, UriKind.Absolute)
                                            }).ToList();
        // close
        str.Close();

        // add results to the list
        XmlItems.Clear();
        foreach (RssFeedItem item in rssFeedItems)
        {
           XmlItems.Add(item);
        }
    };
    client.OpenReadAsync(new Uri(xmlUrl, UriKind.Absolute));
}

xmlUrl是Web上XML文件的路径. XmlItem是这样的类-

xmlUrl is the path to the XML file on the web. XmlItem is a class like so -

public class XmlItem
{
  public string Title { get; set; }
  public string Description { get; set; }
  public Uri Url { get; set; }
}

您需要注意,如果要更新可观察的集合,则可能会遇到跨线程异常.在上面的示例中,XmlItems是List<XmlItem>.但是,如果您希望将XMLItem添加到可观察的集合中,请改用这段代码-

You need to note that you may encounter cross-thread exception if you are updating an observable collection. In the above example, XmlItems is a List<XmlItem>. However, if you wish to add the XMLItem's to an observable collection, use this piece of code instead -

Dispatcher.BeginInvoke(() =>
{
  XmlItems.Clear();
  foreach (RssFeedItem item in rssFeedItems)
  {
     XmlItems.Add(item);
  }
});

另一种方法是使用HttpWebRequest.您可以在此处了解此方法,并使用示例中的代码.

An alternative approach is to use HttpWebRequest. You can read about this approach here and use the code in the sample.

HTH,indyfromoz

HTH, indyfromoz

这篇关于从网站将XML文件加载到XDocument(Silverlight和Windows Phone 7)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 16:30