LINQ到XML的调节特性 [英] Linq to XML conditioning attribute
本文介绍了LINQ到XML的调节特性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的XML
<DataSet xmlns="http://www.bnr.ro/xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.bnr.ro/xsd nbrfxrates.xsd">
<Header>
<Publisher>National Bank of Romania</Publisher>
<PublishingDate>2016-03-24</PublishingDate>
<MessageType>DR</MessageType>
</Header>
<Body>
<Subject>Reference rates</Subject>
<OrigCurrency>RON</OrigCurrency>
<Cube date="2016-03-24">
<Rate currency="EUR">4.4655</Rate>
</Cube>
<Cube date="2016-03-23">
Rate currency="EUR">4.4641</Rate>
</Cube>
</Body>
</DataSet>
我要验证的立方属性的日期接收从昨天日期的欧元价值。
I want to verify the Cube Attribute date to receive the EUR value from yesterday date.
例如,如果今天是2016年3月24日我希望收到来自值 4.4641 2016年3月23日。
For example if today is 2016-03-24 I want to receive the value 4.4641 from 2016-03-23.
我试着用的LINQ to XML
I tried with LINQ to XML
string date_yesterday = DateTime.Now.AddDays(-1).Date.ToString("yyyy-MM-dd");
XElement root = XElement.Parse(sbXmlText.ToString());
IEnumerable<XElement> adress =
from el in root.Descendants("Cube")
let z = el.ElementsAfterSelf().FirstOrDefault()
where z != null && (string)el.Attribute("date") == date_yesterday
select el;
foreach (XElement el in adress)
Console.WriteLine(el);
和尝试
string date_yesterday = DateTime.Now.AddDays(-1).Date.ToString("yyyy-MM-dd");
XElement root = XElement.Parse(sbXmlText.ToString());
IEnumerable<XElement> adress =
root.Descendants("Cube").Where(r => r.Attribute("date").Value == date_yesterday);
foreach (XElement el in adress)
Console.WriteLine(el);
和返回每次空
推荐答案
您有XML的默认命名空间的。您可以使用的的XNamespace
+元素的本地名称的引用元素的命名空间,例如:
Your XML has default namespace. You can use "XNamespace
+element's local-name" to reference element in namespace, for example :
var xml = @"<DataSet xmlns='http://www.bnr.ro/xsd'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:schemaLocation='http://www.bnr.ro/xsd nbrfxrates.xsd'>
<Header>
<Publisher>National Bank of Romania</Publisher>
<PublishingDate>2016-03-24</PublishingDate>
<MessageType>DR</MessageType>
</Header>
<Body>
<Subject>Reference rates</Subject>
<OrigCurrency>RON</OrigCurrency>
<Cube date='2016-03-24'>
<Rate currency='IDR'>1.1111</Rate>
<Rate currency='EUR'>4.4655</Rate>
</Cube>
<Cube date='2016-03-23'>
<Rate currency='EUR'>4.4641</Rate>
</Cube>
</Body>
</DataSet>";
var doc = XDocument.Parse(xml);
//XNamespace that reference default namespace URI:
XNamespace d = "http://www.bnr.ro/xsd";
var yesterday = DateTime.Now.AddDays(-1).Date;
//Use `XNamespace+element's local-name` to reference element in namespace:
var result = (from cube in doc.Descendants(d+"Cube")
from rate in cube.Elements(d+"Rate")
where
((DateTime)cube.Attribute("date")).Date == yesterday
&&
(string)rate.Attribute("currency") == "EUR"
select (decimal)rate
).FirstOrDefault();
Console.WriteLine(result);
输出:
4.4641
这篇关于LINQ到XML的调节特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文