How do I load an xml file in XDocument in Silverlight?

前端 未结 1 834
日久生厌
日久生厌 2021-01-16 18:44

XDocument has no load method contrary to XMLDocument so how do I load an XML content from the Internet with an url ?

相关标签:
1条回答
  • 2021-01-16 19:18

    Actually, XDocument does have a Load(Uri) method, but it's only for navigating to pages within your app. It's a static method, so you do XDocument xDoc = XDocument.Load("/somepage.xaml");. The documentation for the Load(string) method is here.

    If you want to access an external URL, you need to use the WebClient class. Here's an example that I just tested in a Windows Phone 7 app (which is basically SL3):

    using System;
    using System.Net;
    using Microsoft.Phone.Controls;
    using System.Xml.Linq;
    
    namespace XDocumentTest
    {
        public partial class MainPage : PhoneApplicationPage
        {
            // Constructor
            public MainPage()
            {
                InitializeComponent();
                WebClient wc = new WebClient();
                wc.DownloadStringCompleted += HttpsCompleted;
                wc.DownloadStringAsync(new Uri("http://twitter.com/statuses/public_timeline.xml"));
            }
    
            private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)    
            {        
                if (e.Error == null)        
                {            
                    XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);            
                    TextBlock1.Text = xdoc.FirstNode.ToString();        
                }    
            }
        }
    }
    

    This question is similar, but involves https, which I don't think you're dealing with.

    0 讨论(0)
提交回复
热议问题