博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WPF中两种设计模式操作XML转实体类
阅读量:4135 次
发布时间:2019-05-25

本文共 7085 字,大约阅读时间需要 23 分钟。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Reflection;
using System.Xml;
using System.Text;
namespace Test
{
    public class Helper
    {
        private static void SetPropertyByAttribute(object obj, XAttribute attr)
        {
            PropertyInfo property = obj.GetType().GetProperty(attr.Name.LocalName);
            //MethodInfo[] convs = property.PropertyType.GetMethods();
            //MethodInfo conv = property.PropertyType.GetMethod("op_Explicit", convParamTypes);
            property.SetValue(obj, Convert.ChangeType(attr.Value, property.PropertyType, null), null);
        }
        public static List<T> ParseXmlToList<T>(XElement element) where T : new()
        {
            try
            {
                List<T> list = new List<T>();
                Type type = Type.GetType("FreeForm." + element.Name.ToString().Substring(0, element.Name.ToString().Length - 1));
                IEnumerable<XElement> elms = element.Descendants();
                foreach (XElement elem in elms)
                {
                    object obj = Activator.CreateInstance(type);
                    Type[] convParamTypes = new Type[] { typeof(string) };
                    IEnumerable<XAttribute> attributes = elem.Attributes();
                    foreach (XAttribute attr in attributes)
                    {
                        SetPropertyByAttribute(obj, attr);
                    }
                    list.Add((T)obj);
                }
                return list;
            }
            catch
            {
                return null;
            }
        }
        public static List<T> XmlToObjList<T>(string xml, string headtag)
            where T : new()
        {
            List<T> list = new List<T>();
            XmlDocument doc = new XmlDocument();
            PropertyInfo[] propinfos = null;
            doc.LoadXml(xml);
            
            XmlNodeList nodelist = doc.SelectNodes("/" + headtag + "/item");
            foreach (XmlNode node in nodelist)
            {
                T entity = new T();
                //初始化propertyinfo
                if (propinfos == null)
                {
                    Type objtype = entity.GetType();
                    propinfos = objtype.GetProperties();
                }
                //填充entity类的属性
                foreach (PropertyInfo propinfo in propinfos)
                {
                    XmlNode cnode = node.SelectSingleNode(propinfo.Name);
                    string v = cnode.InnerText;
                    if (v != null)
                        propinfo.SetValue(entity, Convert.ChangeType(v, propinfo.PropertyType), null);
                }
                list.Add(entity);
            }
            return list;
        }
        public static XElement ObjectToXmlAttributes<T>(List<T> enitities, string headtag)
        {
            XElement xm = new XElement(headtag+"s");
            PropertyInfo[] propinfos = null;
            foreach (T obj in enitities)
            {
                //初始化propertyinfo
                if (propinfos == null)
                {
                    Type objtype = obj.GetType();
                    propinfos = objtype.GetProperties();
                }
                XElement child = new XElement(headtag);
                foreach (PropertyInfo propinfo in propinfos)
                {
                   XAttribute xa = new XAttribute(propinfo.Name,propinfo.GetValue(obj, null));
                   child.Add(xa);
                }
                xm.Add(child);
            }
            return xm;
        }
        public static XElement ObjectToXmlNodes<T>(List<T> enitities, string headtag)
        {
            XElement xm = new XElement(headtag + "s");
            PropertyInfo[] propinfos = null;
            foreach (T obj in enitities)
            {
                //初始化propertyinfo
                if (propinfos == null)
                {
                    Type objtype = obj.GetType();
                    propinfos = objtype.GetProperties();
                }
                XElement child = new XElement(headtag);
                foreach (PropertyInfo propinfo in propinfos)
                {
                    XElement xa = new XElement(propinfo.Name, propinfo.GetValue(obj, null));
                    child.Add(xa);
                }
                xm.Add(child);
            }
            return xm;
        }
        public static string ObjectToXmlString<T>(List<T> enitities, string headtag)
        {
            StringBuilder sb = new StringBuilder();
            PropertyInfo[] propinfos = null;
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            sb.AppendLine("<" + headtag + ">");
            foreach (T obj in enitities)
            {
                //初始化propertyinfo
                if (propinfos == null)
                {
                    Type objtype = obj.GetType();
                    propinfos = objtype.GetProperties();
                }
                sb.AppendLine("<item>");
                foreach (PropertyInfo propinfo in propinfos)
                {
                    sb.Append("<");
                    sb.Append(propinfo.Name);
                    sb.Append(">");
                    sb.Append(propinfo.GetValue(obj, null));
                    sb.Append("</");
                    sb.Append(propinfo.Name);
                    sb.AppendLine(">");
                }
                sb.AppendLine("</item>");
            }
            sb.AppendLine("</" + headtag + ">");
            return sb.ToString();
        }
       
    }
}
 

 

 

 

 

 

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Xml.Linq;
namespace FreeForm
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Xml.Linq.XElement sample = System.Xml.Linq.XElement.Parse(
           "<Element a=\"3\" b=\"Havarti\" modeSel=\"Complex\" />");
 
            Element c1 = Element.ParseXml(sample);
            Element c2 = XmlToEntityWrapper.ParseXml(sample) as Element;
        }
    }
    public class ModeSelection
    {
        private int mode;
        bool isPassed;
        public bool Validate(string input)
        {
            if (input == "Complex")
            {
                this.isPassed = true;
                return true;
            }
            else
            {
                this.isPassed = false;
                return false;
            }
        }
        public static explicit operator ModeSelection(string value)
        {
            ModeSelection result = new ModeSelection();
            if (String.Compare(value, "Simple", true) == 0)
                result.mode = 1;
            else if (String.Compare(value, "Complex", true) == 0)
                result.mode = 2;
            else if (!int.TryParse(value, out result.mode))
                throw new FormatException("Cannot convert value to type " + result.GetType().Name);
            return result;
        }
        string Name
        {
            get;
            set;
        }
        string Description
        {
            get
            {
                switch (mode)
                {
                    case 1:
                        return "Simple";
                    case 2:
                        return "Complex";
                    default:
                        return "Other";
                }
            }
        }
    }
    public static class XmlToEntityWrapper
    {
        public static object ParseXml(System.Xml.Linq.XElement element)
        {
            try
            {
                Type type = Type.GetType("FreeForm." + element.Name);
                object obj = Activator.CreateInstance(type);
                Type[] convParamTypes = new Type[] { typeof(string) };
                IEnumerable<XAttribute> attributes = element.Attributes();
                foreach (XAttribute attr in attributes)
                {
                    PropertyInfo property = obj.GetType().GetProperty(attr.Name.LocalName);
                    MethodInfo[] convs = property.PropertyType.GetMethods();
                    MethodInfo conv = property.PropertyType.GetMethod("op_Explicit", convParamTypes);
                    //MethodInfo exeValidate = property.PropertyType.GetMethod("Validate");
                    //if (exeValidate != null)
                    //{
                    //    property.SetValue(obj, exeValidate.Invoke(null, new object[] { attr.Value }), null);
                    //}
                    if (conv != null)
                    {
                        property.SetValue(obj, conv.Invoke(null, new object[] { attr.Value }), null);
                    }
                    else
                    {
                        property.SetValue(obj, Convert.ChangeType(attr.Value, property.PropertyType), null);
                    }
                }
                return obj;
            }
            catch
            {
                return null;
            }
        }
    }
    public abstract class XmlToEntity<T> where T : XmlToEntity<T>, new()
    {
        public static T ParseXml(System.Xml.Linq.XElement element)
        {
            object e = (T)Activator.CreateInstance(Type.GetType("FreeForm." + element.Name));
            Type[] convParamTypes = new Type[] { typeof(string) };
            IEnumerable<XAttribute> attributes =element.Attributes();
            foreach (XAttribute attr in attributes)
            {
                PropertyInfo property = e.GetType().GetProperty(attr.Name.LocalName);
                //MethodInfo[] convs = property.PropertyType.GetMethods();
                MethodInfo conv = property.PropertyType.GetMethod("op_Explicit", convParamTypes);
                if (conv != null)
                {
                    property.SetValue(e, conv.Invoke(null, new object[] { attr.Value }), null);
                }
                else
                    property.SetValue(e, Convert.ChangeType(attr.Value, property.PropertyType), null);
            }
            return (T)e;
        }
        public XmlToEntity()
        {
            Elements = new List<T>();
        }
        public IList<T> Elements
        {
            get;
            set;
        }
    }
    public class Elements
    {
        public List<Element> Elements
        {
            get;
            set;
        }
    }
    public class Element : XmlToEntity<Element>
    {
        int _a;
        string _b;
        public string b
        {
            get { return _b; }
            set { _b = value; }
        }
        ModeSelection _modeSel;
        public ModeSelection modeSel
        {
            get { return _modeSel; }
            set { _modeSel = value; }
        }
        public int a
        {
            get
            {
                return _a;
            }
            set
            {
                _a = value;
            }
        }
    }
}

转载地址:http://ltpvi.baihongyu.com/

你可能感兴趣的文章
spring事务探索
查看>>
浅谈Spring声明式事务管理ThreadLocal和JDKProxy
查看>>
初识xsd
查看>>
java 设计模式-职责型模式
查看>>
构造型模式
查看>>
svn out of date 无法更新到最新版本
查看>>
java杂记
查看>>
RunTime.getRuntime().exec()
查看>>
Oracle 分组排序函数
查看>>
删除weblogic 域
查看>>
VMware Workstation 14中文破解版下载(附密钥)(笔记)
查看>>
日志框架学习
查看>>
日志框架学习2
查看>>
SVN-无法查看log,提示Want to go offline,时间显示1970问题,error主要是 url中 有一层的中文进行了2次encode
查看>>
NGINX
查看>>
Qt文件夹选择对话框
查看>>
1062 Talent and Virtue (25 分)
查看>>
1061 Dating (20 分)
查看>>
1060 Are They Equal (25 分)
查看>>
83. Remove Duplicates from Sorted List(easy)
查看>>