说明:通过xml完成用户登录信息的判断
1 搭建UI页面
2 新建一个student类,类中包含以上属性
public class Student { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } public char Gender { get; set; } }
Student
3 页面加载时,先获取xml文件(包含了多个student)
4 首先进行添加
4.1 先判断文件是否存在
存在:加载 不存在:创建并添加
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; namespace XML_Login { public partial class Form1 : Form { public Form1() { InitializeComponent(); } List<Student> list = new List<Student>(); //1创建xml对象 XmlDocument doc = new XmlDocument(); private void Form1_Load(object sender, EventArgs e) { } #region 01创建文件 public void CreateFile() { //1创建声明信息 XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.AppendChild(dec); //2创建person根节点 XmlElement person = doc.CreateElement("Person"); doc.AppendChild(person); AddNode(person); } #endregion #region 03添加节点 private void AddNode(XmlElement person) { //3创建Student子节点 XmlElement student = doc.CreateElement("Student"); person.AppendChild(student); //4Student子节点设置属性Id student.SetAttribute("ID", txtID.Text.Trim()); //5Student添加Name节点 XmlElement name = doc.CreateElement("Name"); name.InnerText = txtName.Text.Trim(); student.AppendChild(name); //5Student添加Age节点 XmlElement age = doc.CreateElement("Age"); age.InnerText = txtAge.Text.Trim(); student.AppendChild(age); //6Student添加Gender节点 XmlElement gender = doc.CreateElement("Gender"); if (RDMan.Checked == true) { gender.InnerText = "男"; } else { gender.InnerText = "女"; } student.AppendChild(gender); } #endregion #region 04判断studentID是否存在 public bool IsExist() { doc.Load("Person.xml"); //1 获取根节点 XmlElement person = doc.DocumentElement; //2 获取所有student的属性 XmlNodeList students = person.ChildNodes; List<string> listID = new List<string>(); foreach (XmlNode item in students) { listID.Add(item.Attributes["ID"].Value); } if (listID.Contains(txtID.Text)) { return true; } return false; } #endregion #region 04"添加"按钮触发事件 private void btnAdd_Click(object sender, EventArgs e) { int Id; if (!int.TryParse(txtID.Text.Trim(), out Id)) { MessageBox.Show("ID请输入正整数"); return; } if (File.Exists("Person.xml")) { //判断student ID是否存在 if (IsExist()) { MessageBox.Show("ID已存在"); return; } //添加节点 doc.Load("Person.xml"); XmlElement person = doc.DocumentElement; AddNode(person); } else { //创建文件--同时把当前页面的Student信息保存到文件中 CreateFile(); } doc.Save("Person.xml"); MessageBox.Show("保存成功!"); } #endregion } }
5
时间: 2024-11-01 20:56:50