using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.IO; using System.Data; namespace VS_CSharp2008_WinForm_Orders0716 { class LoadXML { public void XML_Init() { //if (!File.Exists(@"XML/myconf.xml")) { CreateXmlFile(@"XML/myconf.xml", "MyConfig"); } //if (!File.Exists(@"XML/user.xml")) { CreateXmlFile(@"XML/user.xml", "User"); CreateDefaultUser(); } //LoadUser loadUser = new LoadUser(); //loadUser.USER_Init(); // loading myconf.xml // 条件删除节点 XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(@"XML/myconf.xml"); foreach (XmlNode p in xmldoc.DocumentElement.ChildNodes) { //Console.WriteLine(xmldoc.DocumentElement.ChildNodes.Count); foreach (XmlNode p1 in p.ChildNodes) { //Console.WriteLine(xmldoc.DocumentElement.ChildNodes.Count); Console.WriteLine(p1.ChildNodes[0].Value); if (p1.ChildNodes[0].Value == "adfs") { xmldoc.DocumentElement.RemoveChild(p1.ParentNode); xmldoc.Save(@"XML/myconf.xml"); break; } } } } private void CreateXmlFile(string strFilePath, string strRootElement) { // 方法一: // XmlTextWriter.Create(strFilePath); // 方法二: // 创建xmldoc XmlDocument xmldoc = new XmlDocument(); XmlDeclaration xmldecl = xmldoc.CreateXmlDeclaration("1.0", Encoding.Unicode.EncodingName, null); xmldoc.AppendChild(xmldecl); // 加入根元素 XmlElement rootElement = xmldoc.CreateElement(strRootElement); xmldoc.AppendChild(rootElement); // 加入根的子节点 //XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.Element, "price", null); //xmlnode.InnerText = "19.95"; //xmldoc.DocumentElement.AppendChild(xmlnode); // 保存 xmldoc.Save(strFilePath); } private void CreateDefaultUser() { string[] accountName = new string[] { "Admin", "User", "Guest" }; XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(@"XML/user.xml"); for (int i = 0; i < accountName.Length; i++) { XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.Element, "account" + i, null); xmlnode.InnerText = accountName[i]; XmlAttribute xmlattr = xmldoc.CreateAttribute("pwd"); xmlattr.Value = Encrypt(accountName[i]); xmldoc.DocumentElement.AppendChild(xmlnode); xmldoc.DocumentElement["account" + i].SetAttributeNode(xmlattr); } xmldoc.Save(@"XML/user.xml"); } private string Encrypt(string strEncrypt) { string EncryptString = string.Empty; System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] md5_s = md5.ComputeHash(System.Text.Encoding.Unicode.GetBytes(strEncrypt)); for (int i = 0; i < md5_s.Length; i++) { EncryptString = EncryptString + md5_s[i].ToString("X"); } return EncryptString; } } class LoadUser { public DataTable userTable; public void USER_Init() { userTable = new DataTable(); XmlTextReader xmlTextReader1 = new XmlTextReader(@"XML/user.xml"); xmlTextReader1.Read(); while (xmlTextReader1.Read()) { if (xmlTextReader1.Value == "Admin") { System.Windows.Forms.MessageBox.Show(xmlTextReader1.Value.ToString()); break; } } } } }