private void btnWrite_Click(object sender, EventArgs e) { if (txtName.Text.Trim().Length == 0) { MessageBox.Show("没有输入学生姓名", "友情提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtName.Focus(); return; } dlgSave.Filter= "*.xml|*.xml"; dlgSave.InitialDirectory=Application.StartupPath + @"\xml"; dlgSave.RestoreDirectory = true; dlgSave.OverwritePrompt = false; if (dlgSave.ShowDialog() == DialogResult.OK) { XmlDocument xmlDoc = new XmlDocument(); FileInfo fi = new FileInfo(dlgSave.FileName); XmlNode root = null; if (!fi.Exists) { flag = true; XmlNode xmlnode = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmlDoc.AppendChild(xmlnode); root = xmlDoc.CreateNode(XmlNodeType.Element, "成绩单", null); xmlDoc.AppendChild(root); } else { flag = false; xmlDoc.Load(dlgSave.FileName); root = xmlDoc.SelectSingleNode("成绩单");//查找<成绩单> } XmlComment xc = xmlDoc.CreateComment(cbComment.Text);//创建一个注释 root.AppendChild(xc); XmlElement xe1 = xmlDoc.CreateElement("学生");//创建一个<学生>节点 xe1.SetAttribute("性别", (rbMen.Checked) ? "男" : "女");//设置该节点性别属性 string sTemp = nudID.Value.ToString(); xe1.SetAttribute("学号", lab0512.Text + ((sTemp.Length == 1) ? "0" : "") + sTemp);//设置该节点学号属性 XmlElement xesub1 = xmlDoc.CreateElement("姓名"); xesub1.InnerText = txtName.Text;//设置文本节点 xe1.AppendChild(xesub1);//添加到<学生>节点中 XmlElement xesub2 = xmlDoc.CreateElement("分数"); XmlElement xesub20 = xmlDoc.CreateElement("语文"); xesub20.InnerText = nudyw.Value.ToString(); xesub2.AppendChild(xesub20); XmlElement xesub21 = xmlDoc.CreateElement("数学"); xesub21.InnerText = nudsx.Value.ToString(); xesub2.AppendChild(xesub21); XmlElement xesub22 = xmlDoc.CreateElement("外语"); xesub22.InnerText = nudwy.Value.ToString(); xesub2.AppendChild(xesub22); xe1.AppendChild(xesub2); XmlElement xesub3 = xmlDoc.CreateElement("城市"); if (cmbCity.SelectedIndex != -1) xesub3.InnerText = cmbCity.SelectedItem.ToString(); else xesub3.InnerText = "本地"; xe1.AppendChild(xesub3); root.AppendChild(xe1);//添加到<bookstore>节点中 xmlDoc.Save(dlgSave.FileName); if (flag) MessageBox.Show("成功生成XML文件!","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Information); else MessageBox.Show("信息已加入XML文件!" , "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information); cbComment.SelectedIndex = 0; nudID.Value = 1; txtName.Text = ""; nudyw.Value = nudsx.Value = nudwy.Value = 60; rbMen.Checked = true; rbWomen.Checked = false; cmbCity.SelectedIndex = 0; } }
运行效果图如下: