我想讀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);
}
}
}
謝謝,當我打印它時,獲取所有元素,我只需要元素 RunTimeStamp>的值,然後將其寫回,你能建議我怎麼能去做。同樣在第一種方法中,我將如何獲取的值並寫入它。謝謝 –
Nomad
@Nomad:哦,我沒有意識到還有更多元素。這很容易... –
@Nomad:編輯了答案。但這只是LINQ to XML的一個非常小的例子 - 我建議您花些時間閱讀關於LINQ to XML的完整教程。周圍有很多東西。 –