Read a xml element and write back the new value of element to xml in C#
I am trying to read abc.xml which has this element
<RunTimeStamp>
9/22/2011 2:58:34 PM
</RunTimeStamp>
I am trying to read the value of the element which the xml file has and store it in a string and once i am done with the processing. I get the current timestamp and write the new timestamp back to the xml file.
Here's my code so far, please help and guide, your help will be appreciated.
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();
开发者_C百科 // after done with the processing.
XmlTextWriter writer = new XmlTextWriter("abc.xml", null);
}
}
}
I personally wouldn't use XmlReader
etc here. I'd just load the whole file, preferrably with LINQ to 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");
Much simpler!
Note that if the value is an XML-format date/time, you can cast to DateTime
instead:
DateTime value = (DateTime) timestampElement;
then later:
timestampElement.Value = DateTime.UtcNow; // Or whatever
However, that will only handle valid XML date/time formats - otherwise you'll need to use DateTime.TryParseExact
etc.
linq to xml is the best way to do it. Much simpler and easier as shown by @Jon
精彩评论