using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace Ewide.Core.Util { public class XmlSerializerUtil { static string[] str = AppDomain.CurrentDomain.BaseDirectory.Split("ewide_core"); static string path = str[0]+ @"ewide_core\Api\Ewide.Core\SeedDataXml\"; public Dictionary ReaderALL() { Dictionary dic = new Dictionary(); DirectoryInfo folder = new DirectoryInfo(path); foreach (FileInfo file in folder.GetFiles()) { //除去.xml 后缀 string className = file.Name.Remove(file.Name.Length - 4, 4); object obj = AppInfo(className); string XmlContext = StreamRead(file.FullName); //实例创建 出 类型集合 var modelList = Activator.CreateInstance(typeof(List<>).MakeGenericType(new Type[] { obj.GetType() })); var list = Deserialize(modelList.GetType(), XmlContext); dic.Add(obj.GetType(), list); } return dic; } private object Deserialize(string xmlContent, Type[] Arrtype) { object obj = null; using (StringReader sr = new StringReader(xmlContent)) { XmlSerializer xmldes = new XmlSerializer(typeof(List), Arrtype); obj = xmldes.Deserialize(sr); } return obj; } private object Deserialize(Type type, string xmlContent) { object obj = null; using (StringReader sr = new StringReader(xmlContent)) { XmlSerializer xmldes = new XmlSerializer(type); obj = xmldes.Deserialize(sr); } return obj; } public string StreamRead(string path) { using (StreamReader reader = new StreamReader(path, Encoding.Default)) { return reader.ReadToEnd(); } } private object AppInfo(string name) { string assemblyName = "Ewide.Core"; string nameSpace = "Ewide.Core"; string fullName = nameSpace + "." + name; object ect = Assembly.Load(assemblyName).CreateInstance(fullName); return ect; } /// /// 写入XML到磁盘 /// /// 类型 /// 数据 /// XML名称 public void WriteXML(Type type, object data, string className) { string writePath = path + className + ".xml"; using (FileStream fs = new FileStream(writePath, FileMode.OpenOrCreate)) { XmlSerializer ser = new XmlSerializer(type); ser.Serialize(fs, data); } } } }