How to: Load an XML File from an Arbitrary URI Location with LINQ to XML
The XDocument.Load methods that take a uri string as a parameter must reference a file that is located in the application's XAP package. If you want to download the file from some other location, follow these steps.
To configure a Silverlight Visual Studio project to run this example
-
In Solution Explorer, add assembly references to System.Xml.Linq.dll and System.Net.dll.
-
Modify your page.xaml file so that it includes the following TextBlock element:
<TextBlock x:Name ="OutputTextBlock" Canvas.Top ="10" TextWrapping="Wrap"/>
-
In the page.xaml source file for your application, add the following using statements (Imports in Visual Basic):
To load an XML file from an arbitrary URI location
-
Create the WebClient object, add the handler, and initiate the request. To request a resource as a stream, you must call an OpenReadAsync method overload.
-
Implement the wc_OpenReadCompleted callback function. This function does the following:
-
Checks the Error property for errors.
-
If there are no errors, gets the data stream and passes it to the XDocument's Load method overload.
private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error != null) { OutputTextBlock.Text = e.Error.Message; return; } using (Stream s = e.Result) { XDocument doc = XDocument.Load(s); OutputTextBlock.Text = doc.ToString(SaveOptions.OmitDuplicateNamespaces); } }
-