[英]Replacing WebClient with offline XDocument
我已经构建了一个完整的Windows Phone 7应用程序(我为之感到骄傲!),但我只是意识到将应用程序中访问的XML文件托管在我的网站上并没有真正的目的。 由于从不需要真正更新它们,所以我认为将其简单地包含在项目中就变得更加有意义。 但是,我从中学到的大多数经验和教程都展示了如何在通过WebClient下载XML数据后将其解析到列表框中。 那么,有没有一种简单的方法可以用脱机XML加载器替换WebClient?
本质上,这就是我的应用程序中要编码的页面数,显然,为了简单起见,我更改了一些特定于我的应用程序目的的名称,以免胡说八道。
namespace WindowsPhoneApplication14.Pages.Other
{
public partial class People : PhoneApplicationPage
{
public People()
{
InitializeComponent();
Dispatcher.BeginInvoke((Action)(() => pplListBox.ItemsSource = ppldata));
WebClient pplWebClient = new WebClient();
pplWebClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ppl_DownloadStringCompleted);
pplWebClient.DownloadStringAsync(new Uri("http://www.mywebsite.com/ppl.xml"));
}
void ppl_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
return;
XElement xmlitem = XElement.Parse(e.Result);
var ppldata = new List<PeopleClass>();
foreach (XElement item in xmlitem.Elements("entry"))
{
var name = item.Element("name");
var namevalue = (name == null) ? null : name.Value;
var age = item.Element("age");
var agevalue = (age == null) ? null : age.Value;
ppldata.Add
(new PeopleClass
{
Name = namevalue,
Age = agevalue,
}
);
}
pplListBox.ItemsSource = ppldata;
}
public class PeopleClass
{
public string Name { get; set; }
public string Age { get; set; }
}
public System.Collections.IEnumerable ppldata { get; set; }
}
}
那么,我可以将WebClient操作换成什么呢?
您会注意到XDocument.Load具有两个主要的替代集。 一个采用流(就像您在XElement.Parse(e.Result)中使用的一样),另一个采用流到XAP中XML文件的路径。
如果您的文档是静态的并且可以与XAP一起发布,则可以使用后者。
我张贴的这个样本就是这种方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.