开发者

Silverlight, open xml from outside application package

开发者 https://www.devze.com 2023-04-09 16:42 出处:网络
I have to open and read an xml file in my Silverlight application. I can\'t put this file in resources (my teacher\'s will). I tried to use this code:

I have to open and read an xml file in my Silverlight application. I can't put this file in resources (my teacher's will). I tried to use this code:

XmlReader reader = XmlReader.Create("products.xml");

but got an error:

Cannot find file 'products.xml' in the application xap package.

This xml file is currently located in Debug folder next to .xap

What should I do to make it work?

XML file(just in case):

<products>
  <product>
    <name>nameA</name>
    <desc>descA</desc>
    <image>imgA</image>
  </product>
  <product>
    <name>nameB</name>
    <desc>descB</desc>
    <image>imgb</image>
  </product>
  <product>
    <name>na开发者_Go百科meC</name>
    <desc>descC</desc>
    <image>imgC</image>
  </product>
</products>

Error caught in returnResult(args.Result); of Anthony's code:

System.Reflection.TargetInvocationException: An exception occurred during the operation, making the result invalid.  Check InnerException for exception details. ---> System.Net.WebException: An exception occurred during a WebClient request. ---> System.NotSupportedException: The URI prefix is not recognized.
   in System.Net.WebRequest.Create(Uri requestUri)
   in System.Net.WebClient.GetWebRequest(Uri address)
   in System.Net.WebClient.OpenReadAsync(Uri address, Object userToken)
   --- The end of stack trace of inner exceptions (my translation) ---
   in System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
   in System.Net.OpenReadCompletedEventArgs.get_Result()
   in ProjektAI.MainPage.<>c__DisplayClass1.<GetStreamFromUri>b__0(Object s, OpenReadCompletedEventArgs args)


You will need the help of WebClient to download the xml file from the web server first. Here is a utility method to help.

 public static void GetStreamFromUri(Uri uri, Action<Stream> returnResult)
 {
      WebClient client = new WebClient();
      client.OpenReadCompleted += (s, args) =>
      {
           returnResult(args.Result);
      };
      client.OpenReadAsync(uri);
 }

Your code would then use:-

GetStreamFromUri(new Uri("products.xml", UriKind.Relative), stream =>
{
     using (stream)
     {
         XmlReader reader = XmlReader.Create(stream);

         // Rest of reader processing code called here.
     }
});

//  Note really really well: **Code here will run before XmlReader processing**

Likely the code you've written so far works synchronously. Silverlight allows resources found in the XAP to be loaded and processed synchronously. However network operations are always asynchronous. Its my guess that "(my teacher's will)" is in fact that you learn this important asynchronous aspect of Silverlight coding and what effect it has on the way you need to code.

0

精彩评论

暂无评论...
验证码 换一张
取 消