Windows Phone使用XML代码从URL获取值 [英] Windows Phone get value from url with xml code

查看:39
本文介绍了Windows Phone使用XML代码从URL获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从此URL获取实时货币汇率: http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=GBP&ToCurrency=LTL

这是我尝试的内容:

public void getRate(string howmuch, string from, string to)
    {
        int hmuch = int.Parse(howmuch);
        string url = "http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=GBP&ToCurrency=LTL";
        var xml = XDocument.Load(url);
        var result = xml.Descendants("double");
        btn.Content = result;
    }
我从XDocument.Load收到一个错误,我需要从文件系统传递URI,而不是从Web传递URL。我在网上找不到在Windows Phone上做这件事的正确方法,只有完整的C#。如何正确获取双标记之间的值?

推荐答案

在大约4小时后找到解决方案


这是我调用函数并转换结果的方式:

double rate = await getRate("GBP", "LTL");
string res = System.Convert.ToString(rate);
output.Text = res;

请注意,必须将从中调用此函数的方法声明为函数本身,否则不能使用aWait运算符。


功能:

public async Task<double> getRate(string from, string to)
        {
            string xml = string.Empty;
            Uri url = new Uri("http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency="+from+"&ToCurrency="+to);
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml");
            var response = await httpClient.GetAsync(url);
            using (var responseStream = await response.Content.ReadAsStreamAsync())
            using (var streamReader = new StreamReader(responseStream))
            {
               xml = streamReader.ReadToEnd();
            }
            XDocument xDoc = XDocument.Parse(xml);
            XNamespace xmlns = "http://www.webserviceX.NET/";
            string value = (string)xDoc.Element(xmlns + "double");
            return System.Convert.ToDouble(value);
        }

也不要忘记包括所需的标题

using System.Net;
using System.Xml;
using System.Xml.Linq;
using System.Net.Http;
using System.Threading.Tasks;

这篇关于Windows Phone使用XML代码从URL获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆