Replacing WebClient with offline XDocument
I have built an entire Windows Phone 7 app (which I'开发者_运维技巧m quite proud of!) but I just realized there is no real purpose for the XML files accessed in my app to be hosted on my website. Since they never really have to be updated I decided it makes much more sense to simply include as part of the project. However, most of my experiences and tutorials I've learned from have shown how to parse XML data into listboxes after downloading them through a WebClient. So, is there an easy way to replace a WebClient with an offline XML loader?
This is essentially how many pages in my app are coded, obviously I changed some of the names specific to the purpose of my app to nonsense about people/names/ages for the sake of simplicity.
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; }
}
}
So what can I swap out the WebClient operation for?
You'll notice XDocument.Load has two main sets of overrides. One takes a stream (like you've used in XElement.Parse(e.Result), the other takes a path to an XML file in your XAP.
You can use the latter if your documents are static and can be published with your XAP.
This sample I posted works that way.
binding a Linq datasource to a listbox
精彩评论