很弱的问题,怎样往XML文件中添加新节点?

cityeremite 2003-12-22 06:29:49
下面的代码是其中一段,我想实现的功能是在已经存在的test.xml文件中继续增加节点,可是每次执行,它都把原xml文件中已有的数据清空了,怎样实现类似文本文件APPEND操作的方法呢?

请高人指点!

XmlTextWriter txtWriter = new XmlTextWriter(@"..\..\test.xml",System.Text.Encoding.UTF8 );
txtWriter.Formatting = Formatting.Indented;
txtWriter.WriteStartDocument(true);
txtWriter.WriteDocType("Employees",null,null,null);
txtWriter.WriteComment("this is a test");
txtWriter.WriteStartElement("Employees");
txtWriter.WriteStartElement("employee",null);
txtWriter.WriteElementString("FirstName","John");
txtWriter.WriteElementString("LastName","Smith");
txtWriter.WriteElementString("DateOfBirth","08/09/1968");
txtWriter.WriteElementString("DateOfJoining","08/09/1998");
txtWriter.WriteEndElement();
txtWriter.WriteEndElement();
txtWriter.Flush();
txtWriter.Close();
...全文
64 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
jinzhijie 2003-12-24
  • 打赏
  • 举报
回复
支持mableboy() 的
巍巍清风 2003-12-24
  • 打赏
  • 举报
回复
用XmlTextWriter是会把原来的文件重写过的,先把它load进来,就不会了。
xixigongzhu 2003-12-24
  • 打赏
  • 举报
回复
这样就可以了:
string filename = @"..\..\test.xml";
XmlDocument doc = new XmlDocument();
if (!File.Exists(filename)) {
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
doc.AppendChild(doc.CreateDocumentType("Employees",null,null,null));
doc.AppendChild(doc.CreateComment("this is a test"));
doc.AppendChild(doc.CreateElement("Employees"));
} else {
doc.Load(filename);
}
XmlElement ele = doc.DocumentElement;
XmlElement child = doc.CreateElement("employee");
XmlElement fname = doc.CreateElement("FirstName");
fname.InnerText = "John";
child.AppendChild(fname);
fname = doc.CreateElement("LastName");
fname.InnerText = "Smith";
child.AppendChild(fname);
fname = doc.CreateElement("DateOfBirth");
fname.InnerText = "08/09/1968";
child.AppendChild(fname);
fname = doc.CreateElement("DateOfJoining");
fname.InnerText = "08/09/1998";
child.AppendChild(fname);
ele.AppendChild(child);
XmlTextWriter txtWriter = new XmlTextWriter(filename,System.Text.Encoding.UTF8 );
txtWriter.Formatting = Formatting.Indented;
doc.WriteTo(txtWriter);
txtWriter.Close();
cdyxh 2003-12-24
  • 打赏
  • 举报
回复
學習中,幫你頂一下
mableboy 2003-12-22
  • 打赏
  • 举报
回复
Root=doc.DoumentElement;
XmlNode node=root.CreateElement();
node.InnerXml="<name>mableboy</name";
root.AppendChild(node);

这个具体加到哪儿,你只要定位到她的父节点就可以了!
dldl 2003-12-22
  • 打赏
  • 举报
回复
严重同意楼上意见
luyiping 2003-12-22
  • 打赏
  • 举报
回复
也有append之类的方法啊

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧