Loading local xml file in Windows Phone 7 (WP7)
I am trying to load up an XML file that lives in my Windows Phone 7 solution. I'd like to know the proper way to include the file in the project and then reference it with code. My current code is giving me an error of
NotSupportedException "An exception occurred during a WebClient request."
here is the stub of my WebClient code
WebClient workbenchAdConfigRequest = new WebClient();
workbenchAdConfigRequest.OpenRead开发者_StackOverflow中文版Completed += new OpenReadCompletedEventHandler(workbenchAdConfigRequest_OpenReadCompleted);
workbenchAdConfigRequest.OpenReadAsync(new Uri("/SampleData/SampleData.xml", UriKind.Relative));
and the event handler is
private void workbenchAdConfigRequest_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
XElement xml = XElement.Load(e.Result);
}
catch
{
//return
}
}
on the file /SampleData/SampleData.xml I have set the properties to be
Build Action: Embedded Reference Copy to Output Directory: Do Not Copy Custom Tool: MSBuild:Compile
Can you load a local file from the "file path" of the application?
You can also set the "Build Action" to "Content" in the properties of your XML file, and then in the code behind:
using System.Xml.Linq;
......
XElement appDataXml;
StreamResourceInfo xml = Application.GetResourceStream(new Uri("yourxmlfilename.xml", UriKind.Relative));
appDataXml = XElement.Load(xml.Stream);
Here is how to load an XML file:
Set the "Build action" to "Resource" in the properties of your XML file, then in code:
using System.Xml.Linq;
......
XElement appDataXml;
StreamResourceInfo xml = Application.GetResourceStream(new Uri("/yourprojectname;component/yourxmlfilename.xml", UriKind.Relative));
appDataXml = XElement.Load(xml.Stream);
Here's a working project I posted on MSDN doing just that that stored XML in the XAP and loads it with XDocument/LINQ, binding the result to a ListBox.
binding a Linq datasource to a listbox
精彩评论