根据时间戳C#的XML删除节点 [英] XML delete node according to timestamp C#
本文介绍了根据时间戳C#的XML删除节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要有关如何基于时间戳自动"删除节点的帮助.特定日期由用户在xml文档中定义,例如2006年9月17日 有人可以给我一个例子吗? 预先感谢!
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 e.g. 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();
推荐答案
假设您要与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日期timestamp
与inputdate
进行了比较,以仅等于日期而不是时间.您可以满足任何条件.
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;
这篇关于根据时间戳C#的XML删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文