你的位置:首页 > ASP.net教程

[ASP.net教程]Xml文件的相关操作


     
     /// <summary> /// 创建/// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCreateobject sender, EventArgs e) { //创建 new //创建文档描述信息 "1.0", "utf-8", null); doc.AppendChild(dec); //创建根节点 "Students"); doc.AppendChild(stu); //创建子节点 "Student"); stu.AppendChild(stu1); //追加子节点 "Stu"); //给追加的子节点添加属性 stu2.SetAttribute("name", "张三"); stu2.SetAttribute("age", "22"); stu2.SetAttribute("sex", "男"); stu2.SetAttribute("password", "cao.119"); stu1.AppendChild(stu2); //保存 string txt+"."); MessageBox.Show("创建"+"成功", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information); }

  
    
     /// <summary> /// 读取/// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnReadobject sender, EventArgs e) { string txt= new +"."); = doc.DocumentElement; = stu.ChildNodes;//得到所有节点 string name = ""; int age = 0; string sex = ""; string pwd = ""; = doc.SelectNodes("Students/Student/Stu"); foreach (in xnl1) { name = node.Attributes["name"].Value;//得到name属性的值 age = int.Parse(node.Attributes["age"].Value);//得到age属性的值 sex = node.Attributes["sex"].Value;//得到sex属性的值 pwd = node.Attributes["password"].Value;//得到password属性的值 }
    //当然 这里是MD5加密,要不要无所谓,自己加来玩玩 MD5 md5 = MD5.Create();//MD5抽象类无法实例化 实例化该方法 byte[] buffer = Encoding.Default.GetBytes(pwd);//将字符串转换为字节数组 byte[] mdbuffer = md5.ComputeHash(buffer);//调用ComputeHash方法把数组传进去 //将字节数组中每个元素ToString(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < mdbuffer.Length; i++) { sb.Append(mdbuffer[i].ToString("x2"));////ToString得到十进制字符串 ToString("x")十六进制字符串 ToString("x2")对齐 } MessageBox.Show(""+"\n姓名:" + name + "\n年龄:" + age + "\n性别:" + sex + "\n密码:" + sb); }

     
     追加节点  
     /// <summary> /// 追加节点 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAddNode_Click(object sender, EventArgs e) { = new if (File.Exists("StudentsInfo.")) { doc.Load("StudentsInfo."); //加载 //得到根节点 //再建立元素进行追加 //创建子节点 "Student"); stu.AppendChild(stu1); //追加子节点 "Stu"); //给追加的子节点添加属性 stu2.SetAttribute("name", "李四"); stu2.SetAttribute("age", "22"); stu2.SetAttribute("sex", "男"); stu2.SetAttribute("password", "cao.119"); stu1.AppendChild(stu2); //保存 doc.Save("StudentsInfo."); MessageBox.Show("追加节点成功", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } }

    删除
     /// <summary> /// 删除/// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnDelobject sender, EventArgs e) { string txt= new +"."); = doc.SelectSingleNode("Students"); //查找单一节点 xnl.RemoveAll(); //删除全部 doc.Save("."); MessageBox.Show("删除"+"子节点成功", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information); }