1

所以我知道当我测试在文本块中显示数据时正在读取文件,但似乎无法将 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

4

2 回答 2

0

这应该适合你

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

double usd,gbp, *etc*;

然后,您可以使用 for each 循环遍历 var 多维数据集中的结果,为每种货币设置一个案例并将其分配给全局变量。下面的示例

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

xml应该是

 <!--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>
于 2012-04-09T01:39:24.663 回答
0

您可能会遇到命名空间问题和我认为的“可怕定义的 XML”问题的组合。XML 具有称为“Cube”的三层节点,这使得解析变得困难。

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

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

    });
于 2012-04-08T17:54:11.763 回答