Export (0) Print
Expand All

How to: Load an XML File from an Arbitrary URI Location with LINQ to XML

Silverlight

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

  1. In Solution Explorer, add assembly references to System.Xml.Linq.dll and System.Net.dll.

  2. Modify your page.xaml file so that it includes the following TextBlock element:

    <TextBlock x:Name ="OutputTextBlock" Canvas.Top ="10" TextWrapping="Wrap"/>
    
  3. In the page.xaml source file for your application, add the following using statements (Imports in Visual Basic):

    
    using System.IO;
    using System.Xml.Linq;
    using System.Net;
    
    
    

To load an XML file from an arbitrary URI location

  1. 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.

    
    WebClient wc = new WebClient();
    wc.OpenReadCompleted += wc_OpenReadCompleted;
    wc.OpenReadAsync(new Uri(uriString));
    
    
    
  2. Implement the wc_OpenReadCompleted callback function. This function does the following:

    1. Checks the Error property for errors.

    2. 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);
        }
    }        
    
    
    

Community Additions

ADD
Show:
© 2014 Microsoft