我已经有一个XML文件,其结构如下:
<?xml version="1.0" encoding="utf-16"?>
<configuration>
<FilePath>C:\Recordings</FilePath>
<Timer>2</Timer>
</configuration>
我想在<configuration>
中再添加一个孩子,并希望新结构如下所示。此外,在添加之前,我还要确保添加的新子项是否存在。
<?xml version="1.0" encoding="utf-16"?>
<configuration>
<FilePath>C:\Recordings</FilePath>
<Timer>2</Timer>
<LastSyncTime>Some Value</LastSyncTime>
</configuration>
如果不存在<LastSyncTime>
,则只应添加,否则不添加。
到目前为止,我已经尝试过:
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);
}
但我得到例外。请为我建议最好的解决方案。 感谢
编辑:我收到以下异常:
[System.InvalidOperationException] = {"The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type."}
答案 0 :(得分:0)
您应该使用XmlNodeType.Element
代替XmlNodeType.Text
。它需要一些其他修复,如下所示:
.....
XmlNodeList nodes = doc.SelectNodes("//LastSyncDateTime");
if (nodes.Count == 0) //Means LastSyncDateTime node does not exist
{
XmlNode mynode = doc.CreateNode(XmlNodeType.Element, "LastSyncDateTime", null);
//set InnerText instead of Value
mynode.InnerText = DateTime.Now.ToString();
//append to root node (DocumentElement)
doc.DocumentElement.AppendChild(mynode);
}
.....