【问题标题】:Get XML from resources, or site从资源或站点获取 XML
【发布时间】:2012-10-30 04:18:50
【问题描述】:

我在最后两个代码行中的 URI 存在一些问题:我尝试从应用程序资源和站点获取 XML。在此之前,我对图像执行了相同的操作 - 一切正常。 cmets 中的异常消息。

// Get image from site: 
// "pack://siteoforigin:,,,/http://www.designdownloader.com/item/pngs/user_f036/user_f036-20111114102144-00003.png"

// Get image from building resources (Build Action = Resources).
Uri uri_male_default = new Uri("pack://application:,,,/male.png");

// Get image from site: 
// "pack://siteoforigin:,,,/http://www.designdownloader.com/item/pngl/user_f046/user_f046-20111114102341-00003.png"

// Get image from building resources (Build Action = Resources).
Uri uri_female_default = new Uri("pack://application:,,,/myImages/famale.png"); 

// Create images (it's works fine):
img_male_default = new BitmapImage(uri_male_default);
img_female_default = new BitmapImage(uri_female_default);

//The next both cases ain't working:
// NotSupportedException: URI prefix isn't recognized.     
XElement xml_1 = XElement.Load("pack://application:,,,/SettingsX.xml"); // Get XML from building resources (Build Action = Resources).
XElement xml_2 = XElement.Load("pack://siteoforigin:,,,/https://skydrive.live.com/?cid=51b3145b64e05fef&id=51B3145B64E05FEF%21550");

XElement.Load 获取一个 URI 作为参数。为什么我不能用 XML 做到这一点?

【问题讨论】:

    标签: c# .net wpf uri


    【解决方案1】:

    从错误描述来看,我非常怀疑是否可以将 WPF 包 URI 传递给 XElement.Load,但您始终可以使用相对路径,它会起作用,示例代码如下:

    Uri uri = new Uri("/SettingsX.xml", UriKind.Relative);
                System.Windows.Resources.StreamResourceInfo info = Application.GetResourceStream(uri); 
                XElement settings = XElement.Load(info.Stream);
    

    编辑:

    从网上获取xml文件:

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        string url = "Your URL...";
        var webClient = new System.Net.WebClient();
        webClient.DownloadStringCompleted += HttpsCompleted;
        webClient.DownloadStringAsync(new Uri(url));
    }
    
    private void HttpsCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
    {
        if (e.Error == null)
        {
            XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
        }
    }
    

    【讨论】:

    • 谢谢!它工作正常:我已经从应用程序资源中读取了 XML。但是从站点读取 XML 文件呢?
    • 我试过这样的方法:WebClient web = new WebClient(); web.DownloadFile("pack://siteoforigin:,,,/https://skydrive.live.com/?cid=51b3145b64e05fef&id=51B3145B64E05FEF%21550", @"c:\temp\temp.xml"); web.DownloadFile("https://skydrive.live.com/?cid=51b3145b64e05fef&id=51B3145B64E05FEF%21550", @"c:\temp\temp2.xml");可能是微软的SkyDrive创建链接,这样的方法无法读取(格式不兼容)?
    • 我有异常:“远程服务器返回错误:(407)需要检查中介的真实性。”。
    • 我已经尝试过这样的 URL(它是我的 SkyDrive):string url = "https://skydrive.live.com/?cid=51b3145b64e05fef&id=51B3145B64E05FEF%21550";
    • 我正在尝试下载 SettingsX.xml 文件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 2019-03-02
    相关资源
    最近更新 更多