【问题标题】:XML delete node according to timestamp C#XML根据时间戳删除节点C#
【发布时间】:2017-01-23 07:21:56
【问题描述】:

我需要有关如何根据时间戳“自动”删除节点的帮助。特定日期由用户在 xml 文档中定义,例如2006 年 9 月 17 日 有人可以给我一个例子吗? 提前致谢!

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

【问题讨论】:

  • 这不是有效的 xml。时间戳节点应该有一个属性,其值为您的实际时间戳。
  • 你的意思是标准的日期时间格式,没错,但上面只是一个演示xml。
  • 既然您的 xml 现在有效,那么您的具体问题是什么?解析xml并识别节点,还是解析ISO日期格式?
  • 我不知道如何使用时间戳功能。我对 LINQ 足够熟悉,识别节点不是问题。谢谢。
  • 请分享您尝试了什么?

标签: c# xml linq timestamp


【解决方案1】:

解析 ISO 8601 日期/时间格式:

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

将日期转换为 DateTime 类型后,您可以使用它来识别您要删除的节点(强烈建议使用 LinQ)。

【讨论】:

  • 感谢您的回复。我已经更新了我的代码。那么我将“转换”与时间属性进行比较?
  • 解析 XML 时,您将使用我提供的代码 sn-p 将字符串类型的时间属性转换为 DateTime,并将此 DateTime 与您用来决定的日期时间进行比较节点是否应该被删除。
【解决方案2】:

假设您想与 DateTime 变量 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 进行了比较,以便仅相等日期而不是时间。你可以有任何你想要的条件。

注意:需要参考使用 System.Globalization;

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

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-03
  • 2022-10-14
  • 1970-01-01
相关资源
最近更新 更多