【问题标题】:XDocument Filter by attribute date valueXDocument 按属性日期值过滤
【发布时间】:2020-06-30 07:38:18
【问题描述】:

我有以下 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();

【问题讨论】:

  • @Fabio 更新了问题以包含我尝试过的内容。
  • 您可能可以尝试使用 TryParseExact 方法解析日期,您可以在其中提供用于 xml 中日期的格式。
  • DateTimeOffset.ParseExact("20200319123000 +0000", "yyyyMMddHHmmss zzzz", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);。如果您需要假设,请使用DateTimeStyles.AssumeLocal
  • 此外,您似乎没有正确解析元素。尝试类似:var elements = xDocument.Descendants("book").Where(b =&gt; b.NodeType == XmlNodeType.Element &amp;&amp; DateTimeOffset.ParseExact(b.FirstAttribute.Value, "yyyyMMddHHmmss zzzz", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) &lt; DateTimeOffset.Now);

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


【解决方案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(); 
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-30
    • 2016-08-21
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 2020-01-20
    相关资源
    最近更新 更多