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

时间:2012-04-08 15:49:25

标签: xml parsing windows-phone-7 converter currency

所以我知道该文件正在读取,因为我测试了在文本块中显示数据但似乎无法将xml解析为我想要的部分,即货币名称和费率,然后将这些添加到列表中选择和执行货币计算后。

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();
    }
}

}

<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>

非常感谢任何想法或帮助 MH

2 个答案:

答案 0 :(得分:0)

您可能遇到了命名空间问题的组合,以及我认为可以定义的&#34;可怕的XML&#34;问题。 XML有三层节点叫做#34; Cube&#34;,这使得解析起来很困难。

我在下面给出的代码并不是生产代码。相反,我把它呈现给你,这样你就可以看到需要解析的不同元素。

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。当你走过它们时能够倾倒出结构的各个部分是非常有帮助的。

---编辑:根据要求,这里是简化的代码---

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));
        });

    });

答案 1 :(得分:0)

这应该对你有用

编辑; 如果这是您想要的,我不知道。在public partial class MainPage

下创建全局变量
double usd,gbp, *etc*;

然后,您可以使用for循环遍历var cube中的结果,为每种货币设置一个case并将其与全局变量对齐。下面的示例

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应该是

 <!--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>