c# 方便操作xml添加刪除修改讀取

分類:編程 時間:2016-11-04
c# 方便操作xml添加刪除修改讀取 標簽: <無>

代碼片段

using system;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
namespace Common
{
    public class ConvertXml<T>
    {
        private string Xmlpath = string.Empty;
        private string Xmlroot = string.Empty;
        private XmlDocument xml = null;
        private XmlNode rootnode = null;
        private MemberInfo minfo;
        private StreamWriter st;
        private List<T> list = new List<T>();
        private XmlKeyAttribute xmlKeyAtt ;
        private XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
        private T t;
        /// <summary>
        /// 構造函數默認加載xml模板物理路徑
        /// </summary>
        /// <param name="Xmlpath">xml模板物理路徑</param>
        /// <param name="T">XML所對應實體類</param>
        public ConvertXml(T tmodel, string Xmlpath = "")
        {
            this.Xmlpath = Xmlpath;
            xml = new XmlDocument();
            if (!string.IsNullOrEmpty(Xmlpath))
            {
                if (!File.Exists(Xmlpath))
                {
                    // st = new StreamWriter(Xmlpath);
                    //   File.Create(Xmlpath);
                    using (FileStream fs = new FileStream(Xmlpath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        list.Add(tmodel);
                        serializer.Serialize(fs, list);
                        // st.Close();
                        fs.Close();
                        fs.Dispose();
                    }
                }

                else
                {
                    try
                    {
                       // st = new StreamWriter(Xmlpath);
                        xml.Load(Xmlpath);
                   
                        minfo = typeof(T);
                        xmlKeyAtt = Attribute.GetCustomAttribute(minfo, typeof(XmlKeyAttribute)) as XmlKeyAttribute;
                        rootnode = xml.SelectSingleNode(xmlKeyAtt.Rootauthor);
                    }
                    catch (Exception e)
                    {

                        throw;
                    }

                }

            }
            this.t = tmodel;
        }
        /// <summary>
        /// 裝載到xml中
        /// </summary>
        /// <returns></returns>
        public bool InsertXml()
        {
            bool save = true;
            try
            {
                Hashtable ht = this.setHt();
                XmlElement xmlEle = xml.CreateElement(Xmlroot);
                foreach (DictionaryEntry item in ht)
                {
                    XmlElement idxml = xml.CreateElement(item.Key.ToString());
                    idxml.InnerText = item.Value =http://www.oschina.net/code/= null ?"" : item.Value.ToString();
                    xmlEle.AppendChild(idxml);
                }
                rootnode.AppendChild(xmlEle);
            }
            catch (Exception e)
            {

                save = false;
            }
            finally
            {
                save = false;
            }
            xml.Save(Xmlpath);
            return save;
        }
        /// <summary>
        /// 反射當前對象序列化到對象中
        /// </summary>
        /// <returns></returns>
        private Hashtable setHt()
        {
            Hashtable ht = new Hashtable();
            Type modelType = t.GetType();
            Xmlroot = modelType.Name;
            try
            {
                foreach (PropertyInfo item in modelType.GetProperties())
                {
                    ht.Add(item.Name, item.GetValue(t, null));
                }
            }
            catch (Exception e)
            {

                throw;
            }

            return ht;
        }
        /// <summary>
        /// 反序列化xml配置文件
        /// </summary>
        /// <returns></returns>
        public List<T> getModel()
        {
            StreamReader strr = new StreamReader(Xmlpath);
            XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
            this.list = (List<T>)serializer.Deserialize(strr);
            strr.Close();
            strr.Dispose();
            return list;
        }
        /// <summary>
        /// 修改一個xml節點值
        /// </summary>
        /// <returns></returns>
        public bool updateModel(ref ValidationErrors err)
        {
            bool save = true;
            XmlNodeList nodelist = rootnode.ChildNodes;
            Type modelType = t.GetType();
            System.Reflection.PropertyInfo propertyInfo = modelType.GetProperty(xmlKeyAtt.Author);
            string tempID = propertyInfo.GetValue(t, null) == null ? "" : propertyInfo.GetValue(t, null).ToString();
            try
            {
                foreach (XmlNode item in nodelist)
                {   
                    XmlElement xe = item as XmlElement;
                    if (xe != null)
                    {
                        foreach (PropertyInfo itemModel in modelType.GetProperties())
                        {
                           
                            if (xe[xmlKeyAtt.Author].InnerText == tempID)
                            {
                                xe[itemModel.Name].InnerText = itemModel.GetValue(t, null) == null ? "" : itemModel.GetValue(t, null).ToString();
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                err.Add(e.ToString());
                save=false;
            }
           
            xml.Save(Xmlpath);
            return save;
        }
        /// <summary>
        /// 刪除一個節點
        /// </summary>
        /// <returns></returns>
        public bool DeleteModel()
        {

            bool save = true;
            XmlNodeList nodelist = rootnode.ChildNodes;
            Type modelType = t.GetType();
            System.Reflection.PropertyInfo propertyInfo = modelType.GetProperty(xmlKeyAtt.Author);
            string tempID = propertyInfo.GetValue(t, null) == null ? "" : propertyInfo.GetValue(t, null).ToString();
            try
            {
                foreach (XmlNode item in nodelist)
                {
                    XmlElement xe = item as XmlElement;
                    if (xe != null)
                    {
                        
                            if (xe[xmlKeyAtt.Author].InnerText == tempID)
                            {
                                rootnode.RemoveChild(item);
                            }
                    }
                }
            }
            catch (Exception e)
            {

                save = false;
            }

            xml.Save(Xmlpath);
            return save;
        }
      }
    }
    
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    [AttributeUsage(AttributeTargets.Class)]
    public  class XmlKeyAttribute:Attribute
    {
        private string _author;
        private string _Rootauthor;
        public XmlKeyAttribute(string _rootauthor, string author="id")
        {
            _author = author;
            _Rootauthor=_rootauthor;
        }
        public string Author
        {
            get { return _author; }
        }
        public string Rootauthor
        {
            get { return _Rootauthor; }
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Common
{
    [Serializable]
    [XmlRoot("ArrayOfRviewModel")]//xml的根節點ArrayOf+類名
    [XmlKey("ArrayOfRviewModel", "ID")]//相當於主鍵字段 添加刪除修改會使用到
  public  class RviewModel
    {
        public string ID
        { get; set; }
        public string Name
        { get; set; }
        /// <summary>
        /// 執行方式
        /// </summary>
        public string Sql
        { get; set; }
        /// <summary>
        /// 執行內容
        /// </summary>
        public string Content
        { get; set; }

    }
}
 //創建xml
 RviewModel model = new RviewModel();
//對象賦值 model.id=1;model.name=2;
 string paht = Server.MapPath("~/XRviewConfig/RviewModel.xml");
            if (!System.IO.File.Exists(paht))
            {
                Common.ConvertXml<RviewModel> xml = new ConvertXml<RviewModel>(model, paht);
            }
            else
            {
                Common.ConvertXml<RviewModel> xml = new ConvertXml<RviewModel>(model, paht);
                xml.InsertXml();
                var item = xml.getModel();
            }

  //查詢單個對象 
  string paht = Server.MapPath("~/XRviewConfig/RviewModel.xml");
  RviewModel model = new RviewModel();
  Common.ConvertXml<RviewModel> xml = new ConvertXml<RviewModel>(model, paht);
  model = xml.getModel().Where(o => o.ID == id).First();

 //修改
  Common.ConvertXml<RviewModel> xml = new ConvertXml<RviewModel>(model, paht);
            xml.UpdateModel(ref validationErrors);
            if (validationErrors != null && validationErrors.Count > 0)
            {
                validationErrors.All(a =>
                {
                    returnValue += a.Errormessage;
                    return true;
                });
            }


//刪除
   string[] deleteId = new String [];
            string paht = Server.MapPath("~/XRviewConfig/RviewModel.xml");
            RviewModel model = new RviewModel();
            Common.ConvertXml<RviewModel> xml = new ConvertXml<RviewModel>(model, paht);
            foreach (var item in deleteId)
            {
                model = xml.getModel().Where(o => o.ID == item).First();
                Common.ConvertXml<RviewModel> tempxml = new ConvertXml<RviewModel>(model, paht);
                if (deleteId != null && deleteId.Length > 0)
                {
                    if (tempxml.DeleteModel())
                    {
                        LogClassModels.WriteServiceLog(Suggestion.DeleteSucceed + ",信息的Id為" + string.Join(",", deleteId), "消息"
                            );//刪除成功,寫入日誌
                        return Json("OK");
                    }
                    else
                    {
                        if (validationErrors != null && validationErrors.Count > 0)
                        {
                            validationErrors.All(a =>
                            {
                                returnValue += a.ErrorMessage;
                                return true;
                            });
                        }
                        LogClassModels.WriteServiceLog(Suggestion.DeleteFail + ",信息的Id為" + string.Join(",", deleteId) + "," + returnValue, "消息"
                            );//刪除失敗,寫入日誌
                    }
                }
            }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Common
{   
    /// <summary>
    /// 驗證錯誤
    /// </summary>
    public class ValidationError
    {
        public ValidationError() { }

        public string ErrorMessage { get; set; }
    }
 
    /// <summary>
    /// 多個驗證錯誤的集合
    /// </summary>
    public class ValidationErrors : List<ValidationError>
    {
        public void Add(string errorMessage)
        {
            base.Add(new ValidationError { ErrorMessage = errorMessage });
        }
    }
  
}

Tags: private public null 標簽

文章來源:


ads
ads

相關文章
ads

相關文章

ad