问题
I am trying to get live currency rate from this url: http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=GBP&ToCurrency=LTL
This is what I tried:
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;
}
I get an error from XDocument.Load that I need to pass URI from filesystem, not URL from web. I didn't found correct way on the web to do this in windows phone, only with full C#. How to properly get that value between double tags?
回答1:
You can try using WebClient
to download XML content from internet :
WebClient wc = new WebClient();
wc.DownloadStringCompleted += DownloadCompleted;
wc.DownloadStringAsync(new Uri(" http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=GBP&ToCurrency=LTL"));
Then use XDocument.Parse()
to load it to XDocument
object :
private void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument xdoc = XDocument.Parse(e.Result);
var result = xml.Root;
btn.Content = result;
}
}
Note that your XML has default namespace so it should be handled a bit differently (your current try won't work even if the XDocument
was created successfully).
回答2:
Found a solution after ~4 hours:
This is how I call my function and convert result:
double rate = await getRate("GBP", "LTL");
string res = System.Convert.ToString(rate);
output.Text = res;
Note that method from which you call this function must be declared async as function itself, otherwise you can't use await operator.
Function:
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);
}
Also don't forget to include needed headers:
using System.Net;
using System.Xml;
using System.Xml.Linq;
using System.Net.Http;
using System.Threading.Tasks;
来源:https://stackoverflow.com/questions/24971191/windows-phone-get-value-from-url-with-xml-code