【问题标题】:XML url to c# objectXML url 到 c# 对象
【发布时间】:2017-11-12 18:16:37
【问题描述】:

我有以下链接:XML File

如您所见,它有一个 XML 文件,其中包含一个名为 currency 的对象,该对象包含一个货币列表。

我有 Currency 类,我需要将该“货币”列表提取到一个对象中 "list<Currency> allCurrencies=...."

这是一个 UWP 项目。 最好没有异步的东西,并且由于某种原因我没有 WebClient 类的 dll。我尝试了很多方法,但总是失败,各种异常。

【问题讨论】:

标签: c# xml serialization uwp stream


【解决方案1】:

使用 XML Linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string URL = "http://www.boi.org.il/currency.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(URL);

            Currency.currencies = doc.Descendants("CURRENCY").Select(x => new Currency() {
                name = (string)x.Element("NAME"),
                unit = (int)x.Element("UNIT"),
                code = (string)x.Element("CURRENCYCODE"),
                country = (string)x.Element("COUNTRY"),
                rate = (decimal)x.Element("RATE"),
                change = (decimal)x.Element("CHANGE")
            }).ToList();
        }
    }
    public class Currency
    {
        public static List<Currency> currencies = new List<Currency>();

        public string name { get; set; }
        public int unit { get; set; }
        public string code { get; set; }
        public string country { get; set; }
        public decimal rate { get; set; }
        public decimal change { get; set; }
    }
}

【讨论】:

  • XDocument.Load() 不适用于 URL,它必须是文件路径。它抛出异常 System.Xml.XmlException: 'Cannot open 'boi.org.il/currency.xml'。 Uri 参数必须是文件系统的相对或绝对路径。'
猜你喜欢
  • 1970-01-01
  • 2013-11-15
  • 2012-05-15
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 2010-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多