删除日期值早于今天的节点

时间:2015-01-20 20:21:22

标签: c# xml

在C#应用程序中,如果我有以下XML:

<SyncTable>
  <SyncEntry>
    <Cal_ID>1234</Cal_ID>
    <Cal_LastUpdated>2015-01-20T14:25:34.828-05:00</Cal_LastUpdated>
    <Cal_StartDateTime>2015-01-22T20:05:00-05:00</Cal_StartDateTime>
  </SyncEntry>
  <SyncEntry>
    <Cal_ID>4567</Cal_ID>
    <Cal_LastUpdated>2015-01-20T11:00:24.988-05:00</Cal_LastUpdated>
    <Cal_StartDateTime>2015-02-10T18:30:00-05:00</Cal_StartDateTime>
  </SyncEntry>
</SyncTable>

如何搜索和删除<SyncTable>条目比今天更早的条目<Cal_StartDateTime>

2 个答案:

答案 0 :(得分:0)

有效的XML文档必须具有单个根元素。你的问题&amp;注释意味着您有多个SyncTable,因此我添加了一个根元素以使其有效(SyncTables)。

下面的代码将查看SyncTable中的每个Cal_StartDateTime值,然后使用找到的最大值作为DateTime.Now.Date的比较。

如果您希望使用最小值,请将Max替换为Min

class Program
{
    static void Main(string[] args)
    {
        var xmlString = @"<SyncTables>
<SyncTable>
  <SyncEntry>
    <Cal_ID>1234</Cal_ID>
    <Cal_LastUpdated>2015-01-20T14:25:34.828-05:00</Cal_LastUpdated>
    <Cal_StartDateTime>2015-01-22T20:05:00-05:00</Cal_StartDateTime>
  </SyncEntry>
  <SyncEntry>
    <Cal_ID>4567</Cal_ID>
    <Cal_LastUpdated>2015-01-10T11:00:24.988-05:00</Cal_LastUpdated>
    <Cal_StartDateTime>2015-02-10T18:30:00-05:00</Cal_StartDateTime>
  </SyncEntry>
</SyncTable>
</SyncTables>";

        var xml = XElement.Parse(xmlString);

        var syncTablesToRemove =
            xml.Elements("SyncTable")
                .Where(x =>
                    x.Descendants("Cal_StartDateTime")
                        .Select(y => DateTime.Parse(y.Value)).Max() < DateTime.Now.Date);

        foreach (var syncEntry in syncTablesToRemove)
        {
            syncEntry.Remove();
        }

        Console.WriteLine(xml);

        Console.ReadLine();
    }
}

答案 1 :(得分:0)

这是做你想做的事的一种方式:

string xml = @"
  <SyncTable>
    <SyncEntry>
      <Cal_ID>1234</Cal_ID>
      <Cal_LastUpdated>2015-01-20T14:25:34.828-05:00</Cal_LastUpdated>
      <Cal_StartDateTime>2015-01-22T20:05:00-05:00</Cal_StartDateTime>
    </SyncEntry>
    <SyncEntry>
      <Cal_ID>4567</Cal_ID>
      <Cal_LastUpdated>2015-01-20T11:00:24.988-05:00</Cal_LastUpdated>
      <Cal_StartDateTime>2015-02-10T18:30:00-05:00</Cal_StartDateTime>
    </SyncEntry>
  </SyncTable>
  ";

  XmlDocument doc = new XmlDocument() ;
  doc.LoadXml( xml ) ;

  DateTime       dtNow = DateTime.UtcNow ;
  DateTimeStyles style = DateTimeStyles.AssumeUniversal
                       | DateTimeStyles.AdjustToUniversal
                       | DateTimeStyles.AllowWhiteSpaces
                       ;
  foreach( XmlNode node in doc.SelectNodes( "/SyncTable/SyncEntry/Cal_StartDateTime" ) )
  {
    DateTime startDate ;
    bool isValid = DateTime.TryParseExact( node.InnerText , "yyyy-MM-ddTHH:mm:ssK" , CultureInfo.InvariantCulture , style , out startDate ) ;
    if ( !isValid || startDate < dtNow )
    {
      doc.DocumentElement.RemoveChild(node.ParentNode);
    }
  }

此时,doc删除了所有违规的<SyncEnctry>元素。