Xml Operation Class Summary

来源:互联网 发布:打开telnet端口 编辑:程序博客网 时间:2024/03/29 04:49
using System;using System.Collections.Generic;using System.Linq;using System.Transactions;using System.Xml.Linq;using System.Xml.XPath;using XmlDAL.Interface; namespace XmlDAL.DefaultImplementation{    /// <summary>    /// pass working node parent and path and working node    /// e.g. want to working with config/menu/menuItem :    /// parent path should be ./menu    /// working node is menuItem    /// </summary>    public class XmlOperation : IXmlOperation    {        private readonly XDocument _document;        private readonly string _path;        private readonly XElement _rootElement;        private readonly string _workingNodeParentPath;        private readonly string _workingNode;        public XmlOperation(string filePathstring workingNodeParentPathstring workingNode)        {            _path = filePath;            _document = XDocument.Load(filePath);            _rootElement = _document.Root;            _workingNodeParentPath = workingNodeParentPath;            _workingNode = workingNode;        }         public IXmlOperation SaveElement(XElement element)        {             var ret =                _rootElement.XPathSelectElements(_workingNodeParentPath)                            .First()                            .Descendants(_workingNode)                            .Where(e => e.Attribute("id").Value == element.Attribute("id").Value);             if (!ret.Any())                return this;             using (var scope = new TransactionScope())            {                ret.Remove();                _rootElement.XPathSelectElements(_workingNodeParentPath).First().Add(element);                _rootElement.Save(_path);                scope.Complete();            }             return this;        }         public XDocument Document        {            get { return _document; }        }         public IXmlOperation AppendToLast(XElement element)        {            using (var scope = new TransactionScope())            {                _rootElement.XPathSelectElements(_workingNodeParentPath).First().Add(element);                _rootElement.Save(_path);                scope.Complete();            }             return this;        }         public IXmlOperation RemoveWhere(Func<XElementboolcondition)        {            var ret = _rootElement.XPathSelectElements(_workingNodeParentPath).First().Descendants(_workingNode).Where(condition);            if (!ret.Any())                return this;            using (var scope = new TransactionScope())            {                ret.Remove();                _rootElement.Save(_path);                scope.Complete();            }            return this;        }         public IEnumerable<XElementSearchBy(Func<XElementboolcondition)        {            return _rootElement.XPathSelectElements(_workingNodeParentPath).First().Descendants(_workingNode).Where(condition);        }     }}

 

Usage :

 

using System;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using System.Reflection;using System.Transactions;using Common.Constant;using WorkTrackerBC.Interface.WorkItem;using XmlDAL.DefaultImplementation;using XmlDAL.Interface;using System.Xml.Linq;using Common.Helper;using Entity.Business;using System.Collections.ObjectModel; namespace WorkTrackerBC.DefaultImplementation.WorkItem{    public class WorkItemDomainModel : IWorkItemOperation    {        private readonly IXmlOperation _xmlOperation;        public WorkItemDomainModel()        {            //here accept xPath to indicate working path            _xmlOperation = new XmlOperation(ConfigurationConst.XmlPathWorkTracker".","workItem");        }         public ObservableCollection<Entity.Business.WorkItemAppendWorkItem(Entity.Business.WorkItem item)        {            var newElement = WorkItemToElement(item);            _xmlOperation.AppendToLast(newElement);             return All();        }         public ObservableCollection<Entity.Business.WorkItemAll()        {            return new ObservableCollection<Entity.Business.WorkItem>(_xmlOperation.SearchBy(e => true).Select(ElementToWorkItem));        }         public ObservableCollection<Entity.Business.WorkItemWhere(Expression<Func<Entity.Business.WorkItembool>> whereExp)        {            return new ObservableCollection<Entity.Business.WorkItem>(All().Where(whereExp.Compile()));        }         public IWorkItemOperation UpdateItemById(Guid oldItemIdEntity.Business.WorkItem newItem)        {            var newElement = WorkItemToElement(newItem);            if (!_xmlOperation.SearchBy(e => new Guid(e.Attribute("id").Value) == oldItemId).Any())                return this;             using (var transaction = new TransactionScope(TransactionScopeOption.RequiredTimeSpan.FromMinutes(1)))            {                _xmlOperation.RemoveWhere(e => new Guid(e.Attribute("id").Value) == oldItemId);                _xmlOperation.AppendToLast(newElement);                transaction.Complete();            }            return this;        }         public IWorkItemOperation RemoveById(Guid id)        {            _xmlOperation.RemoveWhere(e => new Guid(e.Attribute("id").Value) == id);            return this;        }         public IWorkItemOperation MarkAsDone(Guid id)        {            var element = _xmlOperation.SearchBy(e => new Guid(e.Attribute("id").Value) == id).First();            element.Attribute("isFinished").SetValue(Boolean.TrueString);            _xmlOperation.SaveElement(element);            return this;        }         public IWorkItemOperation MarkAsToDo(Guid id)        {            var element = _xmlOperation.SearchBy(e => new Guid(e.Attribute("id").Value) == id).First();            element.Attribute("isFinished").SetValue(Boolean.FalseString);            _xmlOperation.SaveElement(element);            return this;        }         public ObservableCollection<Entity.Business.WorkItemGetToDoListBy(Func<Entity.Business.WorkItemboolexp)        {            var todoAll = GetToDoListAll();            return new ObservableCollection<Entity.Business.WorkItem>(todoAll.Where(exp));        }         public ObservableCollection<Entity.Business.WorkItemGetToDoListAll()        {            return new ObservableCollection<Entity.Business.WorkItem>(_xmlOperation.SearchBy(e => e.Attribute("isFinished").Value == Boolean.FalseString).Select(ElementToWorkItem));        }         public ObservableCollection<Entity.Business.WorkItemGetDoneBy(Func<Entity.Business.WorkItemboolexp)        {            var allDone = GetDoneAll();            return new ObservableCollection<Entity.Business.WorkItem>(allDone.Where(exp));        }         public ObservableCollection<Entity.Business.WorkItemGetDoneAll()        {            return new ObservableCollection<Entity.Business.WorkItem>(_xmlOperation.SearchBy(e => e.Attribute("isFinished").Value == Boolean.TrueString).Select(ElementToWorkItem));        }         private XElement WorkItemToElement(Entity.Business.WorkItem item)        {            return new XElement("workItem",                                new XElement("desc"item.Desc),                                new XAttribute("id"item.Id),                                new XAttribute("name"item.Name),                                new XAttribute("workType"EnumHelper.GetEnumNameFrom(item.WorkType)),                                new XAttribute("createDate"item.CreateDate),                                new XAttribute("isFinished"item.IsFinished ? Boolean.TrueString : Boolean.FalseString));        }         private Entity.Business.WorkItem ElementToWorkItem(XElement element)        {            WorkItemType workType;            if (!Enum.TryParse(element.Attribute("workType").Valueout workType)) return null;             var xElement = element.Element("desc");            var strDesc = string.Empty;             if (xElement != null)                strDesc = xElement.Value;             return new Entity.Business.WorkItem                {                    Id = new Guid(element.Attribute("id").Value),                    Name = element.Attribute("name").Value,                    CreateDate = DateTime.Parse(element.Attribute("createDate").Value),                    Desc = strDesc,                    WorkType = workType,                    IsFinished = bool.Parse(element.Attribute("isFinished").Value)                };        }           }}

 

Xml:

<workItems>

<workItem id="" name ="" createDate="" isFinished="">

<desc></desc>

</workItem>

</workItems>

 

 

原创粉丝点击