给你个例子吧,把下面的张三和李四改成你的textbox的值即可!
private void button1_Click_3(object sender, EventArgs e)
{
bool bl_exist;
string str_path = "d:\\test.xml";
XmlDocument xml = new XmlDocument();
XmlNode root;
XmlElement xe, Name, Age;
if (File.Exists(str_path))
{
xml.Load(str_path);
root = xml.SelectSingleNode("root"); //存在就查找根节点
}
else
{
XmlDeclaration declare = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(declare);
root = xml.CreateElement("root"); //不存在就创建根节点
xml.AppendChild(root);
}
XmlNodeList nodelist = xml.SelectNodes("/root/Student"); //必须是正斜杠“/” ,大小写有区别
bl_exist = false;
foreach (XmlNode node in nodelist)
{
if (node.ChildNodes[0].InnerText == "张三")
{
bl_exist = true;
break;
}
}
if (!bl_exist)
{
xe = xml.CreateElement("Student"); //创建元素
Name = xml.CreateElement("Name");
Name.InnerText = "张三";
xe.AppendChild(Name);
Age = xml.CreateElement("Age");
Age.InnerText = "19";
xe.AppendChild(Age);
root.AppendChild(xe);
}
XmlNode node2 = xml.SelectSingleNode("//Student[Name='李四']");
if (node2 == null)
{
xe = xml.CreateElement("Student"); //创建元素
Name = xml.CreateElement("Name");
Name.InnerText = "李四";
xe.AppendChild(Name);
Age = xml.CreateElement("Age");
Age.InnerText = "18";
xe.AppendChild(Age);
root.AppendChild(xe);
}
xml.Save(str_path);
}