c# - 将 LINQ 转换为 XML

标签 c# .net linq linq-to-xml

<?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/

相关文章:

c# - C++实践类似于C#的只读数据成员行为

C# All 复选框外观

c# - 通过自定义属性生成附加代码

c# - 用反射找到合适的构造函数?

c# - 使用linq和automapper在dto中将属性序列化为复杂类型

linq - 如何在正确处理 NULL 值的同时在 LINQ 中连接字符串

c# - 如何获取表单上的所有绑定(bind)源

c# - 我可以为 ASP.NET SOAP Web 服务设置一个可选参数吗

.net - 与源代码安全和批处理文件的持续构建集成

asp.net - 无法返回 JsonResult