using System; using System.Web; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using FantasyCMS.Extensions;
namespace FantasyCMS.BLL.XML { public class BaseService<T> where T : class { public BaseService(string dic, string filePath, string elementName) { Dic = dic; FileName = filePath; ElementName = elementName; string mtpath = HttpContext.Current.Server.MapPath(dic + filePath); XMLPath = mtpath; ElementName = elementName; if (!System.IO.File.Exists(mtpath)) { if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(dic))) System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(dic)); XDocument xdoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes")); XElement Roots = new XElement(elementName); xdoc.Add(Roots); xdoc.Save(XMLPath); } Root = XElement.Load(XMLPath); }
private XElement Root; private static string XMLPath; private string ElementName; private string Dic, FileName;
public IEnumerable<XElement> FindList() { var list = Root.Elements(ElementName); return list; }
public XElement Find(string name, string value) { return Root.Elements(ElementName).FirstOrDefault(m => m.Element(name).Value.Equals(value)); }
public XElement FirstOrDefault() { return FindList().FirstOrDefault(); }
public void Add(T entity) { Type t = typeof(T); XElement db = new XElement(ElementName); foreach (var item in t.GetProperties()) { if ("Id".Equals(item.Name)) db.Add(new XElement("Id", HtmlUtils.GetGuid())); else db.Add(new XElement(item.Name, t.GetProperty(item.Name).GetValue(entity, null))); } Root.Add(db); Root.Save(XMLPath); }
public void Edit(T entity, string name, string value) { XElement db = Find(name, value); if (db != null) { Type t = typeof(T); foreach (var item in t.GetProperties()) { if (t.GetProperty(item.Name).GetValue(entity, null) != null) { db.Element(item.Name).Value = t.GetProperty(item.Name).GetValue(entity, null).ToString(); } } Root.Save(XMLPath); } }
public void Remove(string name, string value) { XElement db = Find(name, value); if (db != null) { db.Remove(); Root.Save(XMLPath); } } } }