在 c# 中解析 URL Xml
Posted
技术标签:
【中文标题】在 c# 中解析 URL Xml【英文标题】:Url Xml Parsing In c# 【发布时间】:2021-08-18 02:37:14 【问题描述】:我想从 xml site 获取数据,但我想要特定数据我想获取 USD/TRY、GBP/TRY 和 EUR/TRY 外汇购买值我不知道如何从数据中拆分这些值我有一个测试控制台程序是这样的
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
分类到列表
【问题讨论】:
请编辑您的问题并添加所需的输出。 【参考方案1】:最好使用 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'
【讨论】:
@OytunTur,很高兴听到建议的解决方案对您有用。请不要忘记将其标记为答案。以上是关于在 c# 中解析 URL Xml的主要内容,如果未能解决你的问题,请参考以下文章