XML delete node according to C # timestamp

I need help on how to "automatically" remove a node based on a timestamp. A specific date is defined by the user inside an XML document, for example. 09/17/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(); 
+2
source share
2 answers

Suppose you want to compare with the 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 matched the xml date of the timestamp for each element with inputDate to equal only the date, not the time. You can choose any condition.

Note: you need to access using System.Globalization;

 using System.Globalization; using System.Xml.Linq; using System.Xml; using System.Linq; 
+2
source

Analysis of the date and time format of ISO 8601:

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

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

+3
source

All Articles