c#中的Url Xml分析



我想从xml网站获得数据,但我想要特定的数据我想获得美元/土耳其里拉、英镑/土耳其里拉和欧元/土耳其里拉外汇购买值我不知道如何从数据中分割这些值我有一个测试控制台程序,就像这个

using System;
using System.Xml;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string XmlUrl = "https://www.tcmb.gov.tr/kurlar/today.xml";
XmlTextReader reader = new XmlTextReader(XmlUrl);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
while (reader.MoveToNextAttribute()) // Read the attributes.
Console.Write(" " + reader.Name + "='" + reader.Value + "'");
Console.Write(">");
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine(reader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
}
}
}

如何从xml 中分割我想要的值

我想要的输出是这个

public class ParaBirimi
{
public decimal ForexBuying { get; set; }
public string Name { get; set; }//Values like USD GBP EUR
}

分类到列表

最好使用LINQ to XML API。自2007年以来,它在.Net Framework中可用。

这是你的出发点。您可以将其扩展为读取任何属性或元素。

XML片段

<Tarih_Date Tarih="28.05.2021" Date="05/28/2021" Bulten_No="2021/100">
<Currency CrossOrder="0" Kod="USD" CurrencyCode="USD">
<Unit>1</Unit>
<Isim>ABD DOLARI</Isim>
<CurrencyName>US DOLLAR</CurrencyName>
<ForexBuying>8.5496</ForexBuying>
<ForexSelling>8.5651</ForexSelling>
<BanknoteBuying>8.5437</BanknoteBuying>
<BanknoteSelling>8.5779</BanknoteSelling>
<CrossRateUSD/>
<CrossRateOther/>
</Currency>
<Currency CrossOrder="1" Kod="AUD" CurrencyCode="AUD">
<Unit>1</Unit>
<Isim>AVUSTRALYA DOLARI</Isim>
<CurrencyName>AUSTRALIAN DOLLAR</CurrencyName>
<ForexBuying>6.5843</ForexBuying>
<ForexSelling>6.6272</ForexSelling>
<BanknoteBuying>6.5540</BanknoteBuying>
<BanknoteSelling>6.6670</BanknoteSelling>
<CrossRateUSD>1.2954</CrossRateUSD>
<CrossRateOther/>
</Currency>
...
</Tarih_Date>

c#

void Main()
{
const string URL = @"https://www.tcmb.gov.tr/kurlar/today.xml";
XDocument xdoc = XDocument.Load(URL);

foreach (XElement elem in xdoc.Descendants("Currency"))
{
Console.WriteLine("CrossOrder: '{1}', Kod: '{1}', CurrencyCode: '{2}', Isim: '{3}', CurrencyName: '{4}'{0}"
, Environment.NewLine
, elem.Attribute("CrossOrder").Value
, elem.Attribute("Kod").Value
, elem.Attribute("CurrencyCode").Value
, elem.Element("Isim").Value
, elem.Element("CurrencyName").Value
);
}
}

输出

CrossOrder: '0', Kod: '0', CurrencyCode: 'USD', Isim: 'USD', CurrencyName: 'ABD DOLARI'
CrossOrder: '1', Kod: '1', CurrencyCode: 'AUD', Isim: 'AUD', CurrencyName: 'AVUSTRALYA DOLARI'

最新更新