前端之家收集整理的这篇文章主要介绍了
Linq to XML 增删改查,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
转自:http://de.cel.blog.163.com/blog/static/5145123620119983945167/
public class DataBaseInfo
{
public string ID { get; set; }
public string Company { get; set; }
public string Server { get; set; }
public string DataBase { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
private static XDocument doc = new XDocument();
public static string filePath = ".\\DataBaseInfo.xml";
public DataBaseInfo() {
doc = XDocument.Load(filePath);
}
public DataBaseInfo(string filepath):this()
{
filePath = filepath;
}
/// <summary>
/// 增
/// </summary>
/// <returns></returns>
public bool Add()
{
XElement db = new XElement("DataBase",new XAttribute("id",ID),new XElement("company",new XAttribute("value",Company)),new XElement("server",Server)),new XElement("database",DataBase)),new XElement("username",UserName)),new XElement("password",Password))
);
try
{
//用XElement的Add方法
//XElement doc = XElement.Load(filePath);
//doc.Add(db);
//用XDocument的Add方法
doc.Element("DataBases").Add(db);
doc.Save(filePath);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 删
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static bool Remove(string id)
{
XElement xe = (from db in doc.Element("DataBases").Elements("DataBase") where db.Attribute("id").Value == id select db).Single() as XElement;
try
{
xe.Remove();
doc.Save(filePath);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 改
/// </summary>
/// <returns></returns>
public bool Modify()
{
XElement xe = (from db in doc.Element("DataBases").Elements("DataBase") where db.Attribute("id").Value.ToString() == ID select db).Single();
try
{
xe.Element("company").Attribute("value").Value = Company;
xe.Element("server").Attribute("value").Value = Server;
xe.Element("database").Attribute("value").Value = DataBase;
xe.Element("username").Attribute("value").Value = UserName;
xe.Element("password").Attribute("value").Value = Password;
doc.Save(filePath);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 查
/// </summary>
/// <returns></returns>
public List<DataBaseInfo> GetAll()
{
List<DataBaseInfo> dbs = (from db in doc.Element("DataBases").Elements("DataBase")
select new DataBaseInfo
{
ID = db.Attribute("id").Value.ToString(),Company = db.Element("company").Attribute("value").Value.ToString(),Server = db.Element("server").Attribute("value").Value.ToString(),DataBase = db.Element("database").Attribute("value").Value.ToString(),UserName = db.Element("username").Attribute("value").Value.ToString(),Password = db.Element("password").Attribute("value").Value.ToString()
}).ToList();
return dbs;
}