2011-09-22 38 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

这不是一个真正的答案... –