XDocument按属性日期值筛选

问题描述 投票:0回答:1

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

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

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

year = 2020,

month = 03,

day = 18,

hours = 12,

分钟= 30,

seconds = 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 elements”中没有返回任何内容,而不是过滤后的节点。

  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();
c# .net xml linq-to-xml xdoc
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(); 
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.