<?xml version="1.0" encoding="UTF-8" ?>
<Accounts>
<Account id="usama" password="3210" lastUpdated="6/16/2011 11:21:59 AM" nextUpdate="6/16/2011 11:36:59 AM">
<SubAccount id="false">
<Url>yahoo</Url>
<Review>not so good</Review>
</SubAccount>
<SubAccount id="false">
<Url>google</Url>
<Review>as good as heard.</Review>
</SubAccount>
</Account>
</Accounts>
假设我想获得所有最后更新日期小于或等于今天(假设 6/17/2011)日期的结果。
所以我的结果应该是这样的。
Accout id =usama ,passwod =3210 ,url=yahoo, review=not so good
Accout id =usama ,passwod =3210 ,url=google, review=as good as heard
到目前为止我已经写了查询
var q = from c in doc.Descendants("Accounts")
from a in c.Descendants("Account")
where a.Attribute("nextUpdate").Value == "6/16/2011 11:36:59 AM"
select new
{
accountName = a.Attribute("id").Value,
password = a.Attribute("password").Value,
url = a.Descendants("SubAccount").Descendants("Url").ToString()
//review=a.Attribute("nextUpdate").Value
}
我正在获取用户名和密码,但我不知道如何获取 URL 和审核。还有如何将 where 子句中的 Attribute("nextUpdate") 转换为日期时间,以便我可以将它与日期进行比较?
最佳答案
试试这个(测试和工作):
DateTime someTime = DateTime.Now;
var q = from a in doc.Descendants("Account")
from sub in a.Elements("SubAccount")
where (DateTime)a.Attribute("nextUpdate") <= someTime
select new
{
accountName = a.Attribute("id").Value,
password = a.Attribute("password").Value,
url = (string)sub.Element("Url").Value,
review = (string)sub.Element("Review").Value
}
这使用了 Linq to XML 提供的 DateTime
转换(另见 here)。
关于c# - 将 LINQ 转换为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6380583/