根据节点

时间:2016-10-28 10:22:04

标签: c# asp.net .net xml linq

我有一个XML,我想根据日期选择一个元素。所以Date后代的日期列表比今天少。

XML具有这样的值

<Dates>
<Department>
 <ID>Food</ID>
 <Date>25-11-2016</Date>
</Department>
<Department>
 <ID>Sport</ID>
 <Date>26-10-2016</Date>
</Department>
</Dates>

现在我只需要选择相应日期小于今天的元素,下面的查询将选择日期并从xml中删除项目。

XDocument newXML = XDocument.Load(new StringReader(xmlValues));
var q = from node in newXML.Descendants("Date")           
        let attr = node.Value where attr != null && DateTime.ParseExact
        (attr, "dd-MM-yyyy", CultureInfo.InvariantCulture) < DateTime.Today    
        select node.Parent;             
q.ToList().ForEach(x => x.Remove());

现在我如何只选择日期少于今天的以下项目?

<Department>
 <ID>Sport</ID>
 <Date>26-10-2016</Date>
</Department>

1 个答案:

答案 0 :(得分:0)

试试这个

            string xml =
                "<Dates>" +
                    "<Department>" +
                     "<ID>Food</ID>" +
                     "<Date>25-11-2016</Date>" +
                    "</Department>" +
                    "<Department>" +
                     "<ID>Sport</ID>" +
                     "<Date>26-10-2016</Date>" +
                    "</Department>" +
                "</Dates>";

            XElement dates = XElement.Parse(xml);

            List<XElement> departs = dates.Descendants("Department").Where(x => DateTime.ParseExact(x.Element("Date").Value, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture) < DateTime.Now).ToList();