How to add new child with value in existing XML file in C# using DOM



I have already an XML file whose structure is like this:



<?xml version="1.0" encoding="utf-16"?>
<configuration>
<FilePath>C:\Recordings</FilePath>
<Timer>2</Timer>
</configuration>


I want to to add one more child in <configuration> and want the new structure like shown below. Moreover, before adding I also want to make sure that the new child added is present or not.



<?xml version="1.0" encoding="utf-16"?>
<configuration>
<FilePath>C:\Recordings</FilePath>
<Timer>2</Timer>
<LastSyncTime>Some Value</LastSyncTime>
</configuration>


If <LastSyncTime> is not there, then and only it should be added otherwise not.


I have tried so far as given below:



try
{
XmlDocument doc = new XmlDocument();
doc.Load(newpath);
XmlNodeList nodes = doc.SelectNodes("LastSyncDateTime");


if(nodes.Count == 0) //Means LastSyncDateTime node does not exist
{
XmlNode mynode = doc.CreateNode(XmlNodeType.Text, "LastSyncDateTime",null);
mynode.Value = DateTime.Now.ToString() + "";
doc.AppendChild(mynode);
}
foreach (XmlNode node in nodes)
{
if (node.LastChild != null)
{
LastSyncDateTime = (node.LastChild.InnerText);
Console.WriteLine("Last Date Time is : " + LastSyncDateTime);
}
}
}
catch (Exception ex)
{
//throw ex;
string str = (String.Format("{0} {1}", ex.Message, ex.StackTrace));
Console.WriteLine(str);
}


But I am getting exception. Please suggest me best working solution for this. Thanks


Tiada ulasan:

Catat Ulasan