2016-09-15 93 views
2

我需要關於如何基於時間戳「自動」刪除節點的幫助。一個特定的日期是由用戶在xml文檔中定義的,例如, 17/9/2006 有人可以給我一個例子嗎? 在此先感謝!XML根據時間戳刪除節點C#

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

這是無效的xml。時間戳節點應該有一個屬性,其值是您的實際時間戳。 – kall2sollies

+0

您的意思是標準的日期時間格式,但是以上只是一個演示xml。 – user46000

+0

由於你的xml現在是有效的,你確切的問題是什麼?解析XML並識別節點,或解析ISO日期格式? – kall2sollies

回答

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

我比較與inputdate每個元素只有日期,而不是時間的平等XML日期timestamp。你可以有任何你想要的條件。

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

using System.Globalization; 
using System.Xml.Linq; 
using System.Xml; 
using System.Linq; 
+0

非常感謝! – user46000

3

解析ISO 8601的日期/時間的格式:

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

一旦轉換爲DateTime類型的時間,就可以使用它識別要刪除的節點(並使用LINQ因爲這是高度推薦的)。

+0

感謝您的回覆。我更新了我的代碼。所以我會比較「轉換」與時間屬性? – user46000

+0

當您解析XML時,您將使用我提供的代碼片段將time屬性(它是string類型)轉換爲DateTime,並將此DateTime與用於決定節點是否應刪除的DateTime進行比較。 – kall2sollies