简体   繁体   中英

XML delete node according to timestamp C#

I need help on how to "automatically" delete a node based on timestamp. A particular date is defined by the user inside a xml document eg 17/9/2006 Can someone provide me an example? Thanks in advance!

   <root>
    <element>
    </element>
    <timestamp time="2016-09-16T13:45:30">
    </timestamp>
    <--how do I delete element based on the given timestamp?-->
    </root>

  //UNTESTED CODE

     XDocument doc = XDocument.Load("time.xml");
     var name = doc.Descendants("root")
        .Where(n => n.Attribute("time").Value == "2016-09-16T13:45:30")
        .Select(n => (string)n) 
        .First(); 
      <--how can I delete it based on timestamp-->
         name.Element("element").Remove();

Parsing ISO 8601 date/time format:

string input = "2016-09-16T13:45:30";
DateTime converted = DateTime.Parse(input, null, DateTimeStyles.RoundtripKind);

Once the date converted to a DateTime type, you can use it identify the node you wish to remove (and using LinQ for that is highly recommended).

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());

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.

Note: You need to refer using System.Globalization;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM