将数据添加到现有xml文件

时间:2013-09-20 13:54:05

标签: c# xml winforms

我正在使用以下语法以下列方式将数据添加到现有的xml文件中:

XmlTextReader Reader = new XmlTextReader("ServerPaths.xml");
        DataSet dsNewList = new DataSet();
        dsNewList.ReadXml(Reader);
        Reader.Close();
        DataTable dt = dsNewList.Tables[0];
        dt.Rows.Add(txtNewServerPath.Text);
        dt.WriteXml("ServerPaths.xml",false);

但是,我在最后一行得到错误:

System.IO.IOException was unhandled
          Message=The process cannot access the file 'C:\Documents and Settings\590000\my documents\visual studio 2010\Projects\EasyDeployer\EasyDeployer\bin\Debug\ServerPaths.xml' because it is being used by another process

请帮助解决此错误。或者还有其他方法吗?

我的xml文件如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<ServerList>
<ServerPath>C:\\Avinash\\Dev1</ServerPath>
<ServerPath>C:\\Avinash\\Dev1</ServerPath>
</ServerList>

我只是想添加新的serverpath ..

1 个答案:

答案 0 :(得分:3)

您也可以尝试将XmlNode添加到xml文档中,如下所示:

XmlDocument xd = new XmlDocument();
xd.Load("ServerPaths.xml");

XmlNode rootNode = xd.DocumentElement;
XmlNode serverPathNode = xd.CreateElement("ServerPath");
serverPathNode.InnerText = txtNewServerPath.Text; // Your value

rootNode.AppendChild(serverPathNode);

xd.Save("ServerPaths.xml");