0

我有以下 XML 结构,我需要使用 LINQ 按属性“日期”对其进行过滤,其中“日期”属性的值小于今天。

属性日期的格式为“yyyymmddhhmmss +Zone”。

例如,在给定的 XML 中第一个节点 date="20200318123000 +0000" 表示:

年=2020,

月=03,

天=18,

小时=12,

分钟=30,

秒=00 &

时区 = UTC +0000。

<?xml version="1.0" encoding="utf-8"?>
<books>
 <book date="20200318123000 +0000">
   <length units="pages">270</length>
   <title>Book 1 Title</title>
   <category>Book 1 Category</category>
   <desc>Book 1 Description</desc>
 </book>
 <book date="20200319123000 +0000">
   <length units="pages">144</length>
   <title>Book 2 Title</title>
   <category>Book 2 Category</category>
   <desc>Book 2 Description</desc>
 </book>
</books>

我尝试使用以下代码执行此操作,但它在“IEnumerable 元素”中不返回任何内容,而不是过滤节点。

  XDocument xDocument = XDocument.Load(fileName);

  DateTime t;

  IEnumerable<XElement> elements = xDocument.Descendants("book")
  .Where(d => d.NodeType == XmlNodeType.Attribute && d.Name.Equals("date") && 
  DateTime.TryParse(d.ToString().Split('+').First().Trim(), out t) && t < 
  DateTime.Today)
  .ToList();
4

1 回答 1

1

尝试以下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<DateTime, List<XElement>> dict = doc.Descendants("book")
                .GroupBy(x => DateTime.ParseExact((string)x.Attribute("date"),"yyyyMMddHHmmss zzzz", System.Globalization.CultureInfo.InvariantCulture), y => y)
                .ToDictionary(x => x.Key, x => x.ToList());

            List<KeyValuePair<DateTime, XElement>> beforeToday = dict.Where(x => x.Key < DateTime.Now.Date).SelectMany(x => x.Value.Select(y => new KeyValuePair<DateTime, XElement>(x.Key, y))).ToList(); 
        }
    }
}
于 2020-03-19T08:00:30.793 回答