首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从在线xml货币馈送解析到wp7应用程序

如何从在线xml货币馈送解析到wp7应用程序
EN

Stack Overflow用户
提问于 2012-04-08 23:49:25
回答 2查看 1.3K关注 0票数 1

因此,我知道文件正在被读取,因为我测试了在文本块中显示数据,但似乎不能将xml分解成我想要的部分,即货币名称和汇率,然后将它们添加到列表中以供选择,并在执行货币计算之后。

代码语言:javascript
复制
using System.Xml.Linq;

namespace Mike_sMoney
{
public partial class MainPage : PhoneApplicationPage
{
    //String curName;
    //double curRate;

    WebClient myClient;
    //public class Rate
    //{
    //    public String curName { get; set; }
    //    public double curRate { get; set; }
    //}

    // Constructor
    public MainPage()
    {
        InitializeComponent();

        myClient = new WebClient();
        myClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(myClient_DownloadStringCompleted);

        string urlRate = "http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml";
        myClient.DownloadStringAsync(new Uri(urlRate));

        //XDocument rateDoc = XDocument.Load(new StringReader(urlRate));

        //var rates = from rate in rateDoc.Descendants("Cube")
        //             select new Rate
        //             {
        //                 curName = rate.Attribute("currency").Value,
        //                 curRate = double.Parse(rate.Attribute("rate").Value)

        //             };

    }

    void myClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error == null)
        {
            //textBlock1.Text = e.Result;
            XElement currencyElements = XElement.Parse(e.Result);

            var curList = from mRate in currencyElements.Descendants("Cube")
                          select new ClassRates
                          {
                              currency=mRate.Element("currency").Value,
                              rate=Convert.ToDouble(mRate.Element("rate").Value)
                          };
            fromListBox.ItemsSource = curList;
        }
        else
        {
            textBlock1.Text = e.Error.ToString();
        }


    }

    private void convertButton_Click(object sender, RoutedEventArgs e)
    {
        double x;
        //string urlRate = "http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml";
        //myClient.DownloadStringAsync(new Uri(urlRate));
        //x = urlRate.getElementsByTagName("rate")[0];

    }

    private void amountTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        amountTextBox.SelectAll();
    }
}

}

代码语言:javascript
复制
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
  <gesmes:subject>Reference rates</gesmes:subject>
  <gesmes:Sender>
    <gesmes:name>European Central Bank</gesmes:name>
  </gesmes:Sender>
  <Cube>
    <Cube time="2012-04-05">
      <Cube currency="USD" rate="1.3068"/>
      <Cube currency="JPY" rate="107.06"/>
      <Cube currency="BGN" rate="1.9558"/>
      <Cube currency="CZK" rate="24.704"/>
      <Cube currency="DKK" rate="7.4397"/>
      <Cube currency="GBP" rate="0.82420"/>
      <Cube currency="HUF" rate="295.95"/>
      <Cube currency="LTL" rate="3.4528"/>
      <Cube currency="LVL" rate="0.6995"/>
      <Cube currency="PLN" rate="4.1707"/>
      <Cube currency="RON" rate="4.3728"/>
      <Cube currency="SEK" rate="8.8134"/>
      <Cube currency="CHF" rate="1.2025"/>
      <Cube currency="NOK" rate="7.5692"/>
      <Cube currency="HRK" rate="7.4820"/>
      <Cube currency="RUB" rate="38.6600"/>
      <Cube currency="TRY" rate="2.3468"/>
      <Cube currency="AUD" rate="1.2710"/>
      <Cube currency="BRL" rate="2.3942"/>
      <Cube currency="CAD" rate="1.3042"/>
      <Cube currency="CNY" rate="8.2398"/>
      <Cube currency="HKD" rate="10.1478"/>
      <Cube currency="IDR" rate="11945.92"/>
      <Cube currency="ILS" rate="4.8967"/>
      <Cube currency="INR" rate="66.8750"/>
      <Cube currency="KRW" rate="1479.25"/>
      <Cube currency="MXN" rate="16.8244"/>
      <Cube currency="MYR" rate="4.0106"/>
      <Cube currency="NZD" rate="1.6026"/>
      <Cube currency="PHP" rate="55.897"/>
      <Cube currency="SGD" rate="1.6476"/>
      <Cube currency="THB" rate="40.511"/>
      <Cube currency="ZAR" rate="10.2687"/>
    </Cube>
  </Cube>
</gesmes:Envelope>

任何想法或帮助都是非常感谢的

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-09 09:39:25

这对你来说应该是可行的

编辑;我不知道这是否是您想要的。在public partial class MainPage下创建全局变量

代码语言:javascript
复制
double usd,gbp, *etc*;

然后,您可以使用for each循环遍历var多维数据集中的结果,为每种货币指定一个case,并将其赋给全局变量。示例如下

代码语言:javascript
复制
void myClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
       if (e.Error == null)
        {

            XElement currencyElements = XElement.Parse(e.Result);

            XNamespace ns = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref";


            var rates= currencyElements.Descendants(ns + "Cube")
               .Where(x => x.Attribute("currency") != null)
               .Select(x => new ClassRates
               {

                   curName = x.Attribute("currency").Value,
                   curRate = Convert.ToDouble(x.Attribute("rate").Value)

               });

            foreach (var result in rates)
            {

                switch (result.curName)
                {
                    case "USD":
                        usd = result.curRate;

                        break;

                    case "GBP":
                        gbp = result.curRate;
                        break;

                    default:
                        break;

                }
                textBlock1.Text = usd.ToString();//displaying on screen
            }



        }
        else
        {
            textBlock1.Text = e.Error.ToString();
        }


public class ClassRates
{
    public String curName { get; set; }
    public Double curRate { get; set; }
}

xaml应该是

代码语言:javascript
复制
 <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <TextBlock Height="30" HorizontalAlignment="Left" Margin="344,6,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" />
        <ListBox ItemsSource="{Binding ClassRates}"  Foreground="Yellow"  Height="478" HorizontalAlignment="Center" Margin="2,28,-13,0" Name="listBox1" VerticalAlignment="Top" Width="431"  TabIndex="10">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <TextBlock Margin="0,0,0,0" FontSize="26" HorizontalAlignment="Left" Name="tbl1" Text="{Binding curName}" VerticalAlignment="Top" />
                        <TextBlock Margin="70,0,0,0" FontSize="26" HorizontalAlignment="Left" Name="tbl2" Text="{Binding curRate}" VerticalAlignment="Top" />


                    </Grid>
                </DataTemplate>

            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
票数 0
EN

Stack Overflow用户

发布于 2012-04-09 01:54:12

您可能遇到了名称空间问题和我认为的“定义糟糕的XML”问题。XML有三层节点,称为"Cube",这使得它很难解析。

下面我给你的代码并不是产品代码。相反,我将它呈现给您,以便您可以看到需要解析的不同元素。

代码语言:javascript
复制
XDocument doc = XDocument.Load(@"c:\temp\xmlfile1.xml");

XNamespace ns = XNamespace.Get("http://www.gesmes.org/xml/2002-08-01");
XNamespace masterNs = XNamespace.Get("http://www.ecb.int/vocabulary/2002-08-01/eurofxref");

var envelope = doc.Element(ns.GetName("Envelope"));

var cubeHolder = envelope.Element(masterNs.GetName("Cube"));

var cubes = cubeHolder.Elements(masterNs.GetName("Cube"));


cubes.ToList().ForEach(cube=>
{

    var cubeCurrencies = cube.Descendants(masterNs.GetName("Cube"));


    cubeCurrencies.ToList().ForEach(currency =>
    {


        var country = currency.Attribute("currency").Value;
        var rate = currency.Attribute("rate").Value;

        System.Console.WriteLine("Country: {0}, rate: {1}", country, rate);
    });

});

顺便说一句,我发现其中一个工具对解决这类问题有不可估量的帮助,那就是LinqPad。当你遍历它们时,能够倾倒出结构的不同部分是非常有帮助的。

-编辑:根据要求,下面是简化的代码

代码语言:javascript
复制
Dictionary<string, decimal> rates = new Dictionary<string, decimal>();

XNamespace ns = XNamespace.Get("http://www.gesmes.org/xml/2002-08-01");
XNamespace masterNs = XNamespace.Get("http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
doc.Element(ns.GetName("Envelope"))
   .Element(masterNs.GetName("Cube"))
   .Elements(masterNs.GetName("Cube"))
   .ToList().ForEach(cube=>
    {

        var cubeCurrencies = cube.Descendants(masterNs.GetName("Cube"));

        cubeCurrencies.ToList().ForEach(currency =>
        {
            var country = currency.Attribute("currency").Value;
            var rate = currency.Attribute("rate").Value;

            rates.Add(country,decimal.Parse(rate));
        });

    });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10064118

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档