我具有以下XML结构,我需要使用LINQ按属性“ date”对它进行过滤,其中“ date”属性的值小于今天。
属性日期的格式为“ yyyymmddhhmmss +区域”。
例如,在给定的XML第一节点date =“ 20200318123000 +0000” 意思是:
year = 2020,
month = 03,
day = 18,
hours = 12,
minutes = 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();
答案 0 :(得分: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();
}
}
}