2011-09-22 68 views
1

我想讀abc.xml具有這種元素讀取XML元素和寫回元素的新價值爲XML C#

  <RunTimeStamp> 
      9/22/2011 2:58:34 PM 
      </RunTimeStamp> 

我想讀的元素的值的xml文件具有並將其存儲在一個字符串中,一旦我完成處理。我得到當前的時間戳並將新的時間戳寫回到xml文件。

這是我的代碼到目前爲止,請幫助和指導,您的幫助將不勝感激。

 using System; 
     using System.Collections.Generic; 
     using System.Linq; 
     using System.Text; 
     using log4net; 
     using System.Xml; 

     namespace TestApp 
     { 
      class TestApp 
      { 

       static void Main(string[] args) 
       { 

        Console.WriteLine("\n--- Starting the App --"); 

        XmlTextReader reader = new XmlTextReader("abc.xml"); 

        String DateVar = null; 

        while (reader.Read()) 
        { 
         switch (reader.NodeType) 
         { 

          case XmlNodeType.Element: // The node is an element. 
           Console.Write("<" + reader.Name); 
           Console.WriteLine(">"); 
           if(reader.Name.Equals("RunTimeStamp")) 
           { 
            DateVar = reader.Value; 
           } 
           break; 

          case XmlNodeType.Text: //Display the text in each element. 
           Console.WriteLine(reader.Value); 
           break; 

          /* 
         case XmlNodeType.EndElement: //Display the end of the element. 
          Console.Write("</" + reader.Name); 
          Console.WriteLine(">"); 
          break; 
          */ 
         } 
        } 
        Console.ReadLine(); 

        // after done with the processing. 
        XmlTextWriter writer = new XmlTextWriter("abc.xml", null); 

       } 
      } 
     } 

回答

8

我個人不會使用XmlReader等在這裏。我只是加載整個文件,最好用LINQ到XML:

XDocument doc = XDocument.Load("abc.xml"); 
XElement timestampElement = doc.Descendants("RunTimeStamp").First(); 
string value = (string) timestampElement; 

// Then later... 
timestampElement.Value = newValue; 
doc.Save("abc.xml"); 

更簡單!

注意,如果該值是一個XML格式的日期/時間,則可以轉換爲DateTime代替:

DateTime value = (DateTime) timestampElement; 

再後來:

timestampElement.Value = DateTime.UtcNow; // Or whatever 

不過,這只有手柄有效的XML日期/時間格式 - 否則您將需要使用DateTime.TryParseExact

+0

謝謝,當我打印它時,獲取所有元素,我只需要元素的值,然後將其寫回,你能建議我怎麼能去做。同樣在第一種方法中,我將如何獲取的值並寫入它。謝謝 – Nomad

+0

@Nomad:哦,我沒有意識到還有更多元素。這很容易... –

+0

@Nomad:編輯了答案。但這只是LINQ to XML的一個非常小的例子 - 我建議您花些時間閱讀關於LINQ to XML的完整教程。周圍有很多東西。 –

-1

linq to xml是最好的方法去做吧。 @Jon所示更簡單,更容易

+1

這不是一個真正的答案... –