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

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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):

    Imports System.IO
    Imports System.Xml.Linq
    Imports System.Net
    
    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.

    Dim wc As WebClient = New WebClient()
    AddHandler wc.OpenReadCompleted, AddressOf wc_OpenReadCompleted
    wc.OpenReadAsync(New Uri(uriString))
    
    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 Sub wc_OpenReadCompleted(ByVal sender As Object, ByVal e As OpenReadCompletedEventArgs)
        If e.Error IsNot Nothing Then
            OutputTextBlock.Text = e.Error.Message
            Return
        End If
        Using s As Stream = e.Result
            Dim doc As XDocument = XDocument.Load(s)
            OutputTextBlock.Text = doc.ToString(SaveOptions.OmitDuplicateNamespaces)
        End Using
    End Sub
    
    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);
        }
    }        
    

See Also

Concepts

Other Resources