Linq to XML增删改查
直接上示例:
XML文件:
<?xml version="1.0" encoding="utf-8"?> <users> <user id="001"> <name>Xi</name> <age>24</age> <sale>male</sale> <address>Haidian</address> </user> </users>
User实体类:
public class User { public string ID { get; set; } public string Name { get; set; } public string Age { get; set; } public string Sale { get; set; } public string Address { get; set; } }
XML文件操作:
#region Operate the xml file public void ConnectToXmml() { if (!File.Exists(path)) { XElement Users = new XElement("users", ""); Users.Save(path); } } public bool AddToXml(User user) { XElement Users = XElement.Load(path); XElement newUser = new XElement("user", new XAttribute("id", user.ID), new XElement("name", user.Name), new XElement("age", user.Age), new XElement("sale", user.Sale), new XElement("address", user.Address) ); var u = Users.Elements("user").Where(uu => uu.Attribute("id").Value == user.ID); if (u.Count() > 0) return false; else { Users.Add(newUser); Users.Save(path); return true; } } public bool UpdateToXml(User user) { XElement Users = XElement.Load(path); var uu = Users.Elements("user").Where(u => u.Attribute("id").Value == user.ID); if (uu.Count() > 0) { XElement newUser = uu.First(); newUser.ReplaceNodes( new XElement("name", user.Name), new XElement("age", user.Age), new XElement("sale", user.Sale), new XElement("address", user.Address) ); Users.Save(path); return true; } else return false; } public bool DeleteFromXml(string ID) { XElement Users = XElement.Load(path); var uu = Users.Elements("user").Where(u => u.Attribute("id").Value == ID); if (uu.Count() > 0) { uu.Remove(); Users.Save(path); return true; } else return false; } public User Queryuser(string ID) { User newUser = null; XElement Users = XElement.Load(path); var uu = Users.Elements("user").Where(u => u.Attribute("id").Value == ID); if (uu.Count() > 0) { XElement xUser = uu.First(); newUser = new User { ID = ID, Name = xUser.Element("name").Value, Age = xUser.Element("age").Value, Sale = xUser.Element("sale").Value, Address = xUser.Element("address").Value, }; } return newUser; } #endregion