且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据时间戳C#的XML删除节点

更新时间:2023-01-09 07:52:46

假设您要与DateTime变量inputDate进行比较.

Lets suppose you want to compare with a DateTime variable inputDate.

// I have formatted yor XML and structured it. "root" is the the parent node. Elements are the child elements of root consisting of timestamp tag.

 string xmlInput =  @"
 <root>
 <element>
 <timestamp time='2016-09-16T13:45:30'>
 </timestamp>
 </element>
 <element>
 <timestamp time='2016-10-16T13:45:30'>
 </timestamp>
 </element>
 </root>";

    XDocument  xdoc = XDocument.Parse(xmlInput);
    xdoc.Descendants("root").Elements("element").
                             Where(x => DateTime.Compare(DateTime.Parse(x.Element("timestamp").Attribute("time").Value,null, DateTimeStyles.RoundtripKind).Date, inputDate.Date) ==0).
                             ToList().ForEach(x => x.Remove());

我已经将每个元素的xml日期timestampinputdate进行了比较,以仅等于日期而不是时间.您可以满足任何条件.

I have compared the xml date timestamp for each element with inputdate for equality of only Date not the time. You can have any condition you want.

注意:您需要使用System.Globalization进行引用;

Note: You need to refer using System.Globalization;

using System.Globalization;
using System.Xml.Linq;
using System.Xml;
using System.Linq;