Xml.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. using System;
  2. using System.Text;
  3. using System.Xml;
  4. using System.Xml.Serialization;
  5. using System.IO;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. using System.Globalization;
  8. using System.IO.Compression;
  9. namespace BaseLibRWFile
  10. {
  11. /// <summary>
  12. /// XMLHelper
  13. /// </summary>
  14. public class XMLHelper
  15. {
  16. /// <summary>
  17. /// Creates the specified node name.
  18. /// </summary>
  19. /// <param name="nodeName">Name of the node.</param>
  20. /// <returns>XmlNode.</returns>
  21. public static XmlNode Create(string nodeName)
  22. {
  23. var doc = new XmlDocument();
  24. XmlNode node = doc.CreateElement(nodeName);
  25. return node;
  26. }
  27. /// <summary>
  28. /// Creates the attribute.
  29. /// </summary>
  30. /// <param name="node">The node.</param>
  31. /// <param name="attributeName">Name of the attribute.</param>
  32. /// <param name="value">The value.</param>
  33. /// <returns>XmlAttribute.</returns>
  34. public static XmlAttribute CreateAttribute(XmlNode node, string attributeName, string value)
  35. {
  36. try
  37. {
  38. XmlDocument doc = node.OwnerDocument;
  39. XmlAttribute attr = doc.CreateAttribute(attributeName);
  40. attr.Value = value;
  41. node.Attributes.SetNamedItem(attr);
  42. return attr;
  43. }
  44. catch (Exception err)
  45. {
  46. string desc = err.Message;
  47. return null;
  48. }
  49. }
  50. /// <summary>
  51. /// Objects to XML.
  52. /// </summary>
  53. /// <param name="config">The configuration.</param>
  54. /// <returns>XmlNode.</returns>
  55. public static XmlNode ObjectToXML(object config)
  56. {
  57. try
  58. {
  59. var xnd = new XmlDocument();
  60. if (config != null)
  61. {
  62. //we need the type to serialize
  63. Type t = config.GetType();
  64. var ser = new XmlSerializer(t);
  65. //will hold the xml
  66. using (var writer = new StringWriter(CultureInfo.InvariantCulture))
  67. {
  68. ser.Serialize(writer, config);
  69. xnd.LoadXml(writer.ToString());
  70. writer.Close();
  71. }
  72. }
  73. return xnd.DocumentElement;
  74. }
  75. catch
  76. {
  77. throw;
  78. }
  79. }
  80. /// <summary>
  81. /// XMLs to object.
  82. /// </summary>
  83. /// <param name="node">The node.</param>
  84. /// <param name="objectType">Type of the object.</param>
  85. /// <returns>System.Object.</returns>
  86. public static object XMLToObject(XmlNode node, Type objectType)
  87. {
  88. object convertedObject = null;
  89. if (node != null)
  90. {
  91. using (var reader = new StringReader(node.OuterXml))
  92. {
  93. var ser = new XmlSerializer(objectType);
  94. convertedObject = ser.Deserialize(reader);
  95. reader.Close();
  96. }
  97. }
  98. return convertedObject;
  99. }
  100. }
  101. /// <summary>
  102. /// Class XmlSerializerHelper.
  103. /// </summary>
  104. public class ClsXml
  105. {
  106. /// <summary>
  107. /// 读取XML文件
  108. /// </summary>
  109. /// <param name="XmlFilePath">The XML file path.</param>
  110. /// <param name="type">The type.</param>
  111. /// <returns>System.Object.</returns>
  112. public static object ReadXML(string XmlFilePath, Type type)
  113. {
  114. object object4Read = null;
  115. var serializer = new XmlSerializer(type);
  116. if (!File.Exists(XmlFilePath))
  117. {
  118. return new object();
  119. }
  120. while (object4Read == null)
  121. {
  122. var stream = new FileStream(XmlFilePath, FileMode.Open);
  123. try
  124. {
  125. object4Read = serializer.Deserialize(stream);
  126. }
  127. finally
  128. {
  129. stream.Close();
  130. }
  131. }
  132. return object4Read;
  133. }
  134. /// <summary>
  135. /// 序列化XML文件
  136. /// </summary>
  137. /// <param name="myDs">My ds.</param>
  138. /// <param name="XmlFilePath">The XML file path.</param>
  139. /// <param name="type">The type.</param>
  140. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  141. public static bool WriteXML(object myDs, string XmlFilePath, Type type)
  142. {
  143. bool flag = true;
  144. StreamWriter writer = null;
  145. var serializer = new XmlSerializer(type);
  146. try
  147. {
  148. writer = new StreamWriter(XmlFilePath, false);
  149. serializer.Serialize(writer, myDs);
  150. }
  151. catch (Exception)
  152. {
  153. flag = false;
  154. }
  155. finally
  156. {
  157. if (writer != null)
  158. {
  159. writer.Close();
  160. }
  161. }
  162. return flag;
  163. }
  164. /// <summary>
  165. /// XMLs the serialize.
  166. /// </summary>
  167. /// <typeparam name="T"></typeparam>
  168. /// <param name="entity">The entity.</param>
  169. /// <returns>System.String.</returns>
  170. public static string XMLSerialize<T>(T entity)
  171. {
  172. var buffer = new StringBuilder();
  173. var serializer = new XmlSerializer(typeof(T));
  174. using (TextWriter writer = new StringWriter(buffer))
  175. {
  176. serializer.Serialize(writer, entity);
  177. }
  178. return buffer.ToString();
  179. }
  180. /// <summary>
  181. /// Des the XML serialize.
  182. /// </summary>
  183. /// <typeparam name="T"></typeparam>
  184. /// <param name="xmlString">The XML string.</param>
  185. /// <returns>T.</returns>
  186. public static T DeXMLSerialize<T>(string xmlString)
  187. {
  188. T cloneObject = default(T);
  189. var buffer = new StringBuilder();
  190. buffer.Append(xmlString);
  191. var serializer = new XmlSerializer(typeof(T));
  192. using (TextReader reader = new StringReader(buffer.ToString()))
  193. {
  194. Object obj = serializer.Deserialize(reader);
  195. cloneObject = (T)obj;
  196. }
  197. return cloneObject;
  198. }
  199. /// <summary>
  200. /// 把对象序列化为字符串
  201. /// </summary>
  202. /// <param name="pObj">The p object.</param>
  203. /// <returns>System.Byte[].</returns>
  204. public static byte[] SerializeObject(object pObj)
  205. {
  206. if (pObj == null)
  207. return null;
  208. var _memory = new MemoryStream();
  209. var formatter = new BinaryFormatter();
  210. formatter.Serialize(_memory, pObj);
  211. _memory.Position = 0;
  212. var read = new byte[_memory.Length];
  213. _memory.Read(read, 0, read.Length);
  214. _memory.Close();
  215. return Compress(read);
  216. }
  217. /// <summary>
  218. /// 把字节反序列化成相应的对象
  219. /// </summary>
  220. /// <param name="pBytes">字节流</param>
  221. /// <returns>object</returns>
  222. public static object DeserializeObject(byte[] pBytes)
  223. {
  224. object _newOjb = null;
  225. if (pBytes == null)
  226. return _newOjb;
  227. var _memory = new MemoryStream(Decompress(pBytes));
  228. _memory.Position = 0;
  229. var formatter = new BinaryFormatter();
  230. _newOjb = formatter.Deserialize(_memory);
  231. _memory.Close();
  232. return _newOjb;
  233. }
  234. /// <summary>
  235. /// Write byte[] to file
  236. /// </summary>
  237. /// <param name="dataSource">The data source.</param>
  238. /// <param name="filePath">The file path.</param>
  239. public static void WriteByteToFile(byte[] dataSource, string filePath)
  240. {
  241. var fs = new FileStream(filePath, FileMode.Create);
  242. //将byte数组写入文件中
  243. fs.Write(dataSource, 0, dataSource.Length);
  244. fs.Close();
  245. }
  246. /// <summary>
  247. /// Read byte from file
  248. /// </summary>
  249. /// <param name="filePath">The file path.</param>
  250. /// <returns>System.Byte[].</returns>
  251. public static byte[] ReadByteFromFile(string filePath)
  252. {
  253. var fs = new FileStream(filePath, FileMode.Open);
  254. //获取文件大小
  255. long size = fs.Length;
  256. var array = new byte[size];
  257. //将文件读到byte数组中
  258. fs.Read(array, 0, array.Length);
  259. fs.Close();
  260. return array;
  261. }
  262. /// <summary>
  263. /// Write object to file
  264. /// </summary>
  265. /// <param name="dataSource">The data source.</param>
  266. /// <param name="filePath">The file path.</param>
  267. public static void WriteObjectToFile(object dataSource, string filePath)
  268. {
  269. var fs = new FileStream(filePath, FileMode.Create);
  270. byte[] arraysource = SerializeObject(dataSource);
  271. //将byte数组写入文件中
  272. fs.Write(arraysource, 0, arraysource.Length);
  273. fs.Close();
  274. }
  275. /// <summary>
  276. /// Read object from file
  277. /// </summary>
  278. /// <param name="filePath">The file path.</param>
  279. /// <returns>System.Object.</returns>
  280. public static object ReadObjectFromFile(string filePath)
  281. {
  282. var fs = new FileStream(filePath, FileMode.Open);
  283. //获取文件大小
  284. long size = fs.Length;
  285. var array = new byte[size];
  286. //将文件读到byte数组中
  287. fs.Read(array, 0, array.Length);
  288. fs.Close();
  289. return DeserializeObject(array);
  290. }
  291. /// <summary>
  292. /// 字符串压缩
  293. /// </summary>
  294. /// <param name="data">The data.</param>
  295. /// <returns>System.Byte[].</returns>
  296. /// <exception cref="Exception"></exception>
  297. public static byte[] Compress(byte[] data)
  298. {
  299. try
  300. {
  301. var ms = new MemoryStream();
  302. var zip = new GZipStream(ms, CompressionMode.Compress, true);
  303. zip.Write(data, 0, data.Length);
  304. zip.Close();
  305. var buffer = new byte[ms.Length];
  306. ms.Position = 0;
  307. ms.Read(buffer, 0, buffer.Length);
  308. ms.Close();
  309. return buffer;
  310. }
  311. catch (Exception e)
  312. {
  313. throw new Exception(e.Message);
  314. }
  315. }
  316. /// <summary>
  317. /// 字符串解压缩
  318. /// </summary>
  319. /// <param name="data">The data.</param>
  320. /// <returns>System.Byte[].</returns>
  321. /// <exception cref="Exception"></exception>
  322. public static byte[] Decompress(byte[] data)
  323. {
  324. try
  325. {
  326. var ms = new MemoryStream(data);
  327. var zip = new GZipStream(ms, CompressionMode.Decompress, true);
  328. var msreader = new MemoryStream();
  329. var buffer = new byte[0x1000];
  330. while (true)
  331. {
  332. int reader = zip.Read(buffer, 0, buffer.Length);
  333. if (reader <= 0)
  334. {
  335. break;
  336. }
  337. msreader.Write(buffer, 0, reader);
  338. }
  339. zip.Close();
  340. ms.Close();
  341. msreader.Position = 0;
  342. buffer = msreader.ToArray();
  343. msreader.Close();
  344. return buffer;
  345. }
  346. catch (Exception e)
  347. {
  348. throw new Exception(e.Message);
  349. }
  350. }
  351. /// <summary>
  352. /// string 压缩
  353. /// </summary>
  354. /// <param name="str">The string.</param>
  355. /// <returns>System.String.</returns>
  356. public static string CompressString(string str)
  357. {
  358. string compressString = "";
  359. byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
  360. byte[] compressAfterByte = Compress(compressBeforeByte);
  361. //compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
  362. compressString = Convert.ToBase64String(compressAfterByte);
  363. return compressString;
  364. }
  365. /// <summary>
  366. /// string 解压缩
  367. /// </summary>
  368. /// <param name="str">The string.</param>
  369. /// <returns>System.String.</returns>
  370. public static string DecompressString(string str)
  371. {
  372. string compressString = "";
  373. //byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
  374. byte[] compressBeforeByte = Convert.FromBase64String(str);
  375. byte[] compressAfterByte = Decompress(compressBeforeByte);
  376. compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
  377. return compressString;
  378. }
  379. /// <summary>
  380. /// XMLs the serialize internal.
  381. /// </summary>
  382. /// <param name="stream">The stream.</param>
  383. /// <param name="o">The o.</param>
  384. /// <param name="encoding">The encoding.</param>
  385. private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
  386. {
  387. if (o == null)
  388. throw new ArgumentNullException(nameof(o));
  389. if (encoding == null)
  390. throw new ArgumentNullException(nameof(encoding));
  391. XmlSerializer serializer = new XmlSerializer(o.GetType());
  392. XmlWriterSettings settings = new XmlWriterSettings();
  393. settings.Indent = true;
  394. settings.NewLineChars = "\r\n";
  395. settings.Encoding = encoding;
  396. settings.IndentChars = " ";
  397. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  398. {
  399. serializer.Serialize(writer, o);
  400. writer.Close();
  401. }
  402. }
  403. /// <summary>
  404. /// 将一个对象序列化为XML字符串
  405. /// </summary>
  406. /// <param name="o">要序列化的对象</param>
  407. /// <param name="encoding">编码方式</param>
  408. /// <returns>序列化产生的XML字符串</returns>
  409. public static string XmlSerialize(object o, Encoding encoding)
  410. {
  411. using (MemoryStream stream = new MemoryStream())
  412. {
  413. XmlSerializeInternal(stream, o, encoding);
  414. stream.Position = 0;
  415. using (StreamReader reader = new StreamReader(stream, encoding))
  416. {
  417. return reader.ReadToEnd();
  418. }
  419. }
  420. }
  421. /// <summary>
  422. /// 将一个对象按XML序列化的方式写入到一个文件
  423. /// </summary>
  424. /// <param name="o">要序列化的对象</param>
  425. /// <param name="path">保存文件路径</param>
  426. /// <param name="encoding">编码方式</param>
  427. public static void XmlSerializeToFile(object o, string path, Encoding encoding)
  428. {
  429. if (string.IsNullOrEmpty(path))
  430. throw new ArgumentNullException(nameof(path));
  431. using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
  432. {
  433. XmlSerializeInternal(file, o, encoding);
  434. }
  435. }
  436. /// <summary>
  437. /// 从XML字符串中反序列化对象
  438. /// </summary>
  439. /// <typeparam name="T">结果对象类型</typeparam>
  440. /// <param name="s">包含对象的XML字符串</param>
  441. /// <param name="encoding">编码方式</param>
  442. /// <returns>反序列化得到的对象</returns>
  443. public static T XmlDeserialize<T>(string s, Encoding encoding)
  444. {
  445. if (string.IsNullOrEmpty(s))
  446. throw new ArgumentNullException(nameof(s));
  447. if (encoding == null)
  448. throw new ArgumentNullException(nameof(encoding));
  449. XmlSerializer mySerializer = new XmlSerializer(typeof(T));
  450. using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
  451. {
  452. using (StreamReader sr = new StreamReader(ms, encoding))
  453. {
  454. return (T)mySerializer.Deserialize(sr);
  455. }
  456. }
  457. }
  458. /// <summary>
  459. /// 读入一个文件,并按XML的方式反序列化对象。
  460. /// </summary>
  461. /// <typeparam name="T">结果对象类型</typeparam>
  462. /// <param name="path">文件路径</param>
  463. /// <param name="encoding">编码方式</param>
  464. public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
  465. {
  466. if (string.IsNullOrEmpty(path))
  467. throw new ArgumentNullException(nameof(path));
  468. if (encoding == null)
  469. throw new ArgumentNullException(nameof(encoding));
  470. string xml = File.ReadAllText(path, encoding);
  471. return XmlDeserialize<T>(xml, encoding);
  472. }
  473. /// <summary>
  474. /// XMLs the configuration writer.
  475. /// </summary>
  476. /// <typeparam name="T"></typeparam>
  477. /// <param name="obja">The object.</param>
  478. /// <param name="path">The path.</param>
  479. public static void XmlConfigWriter<T>(T obja, string path)
  480. {
  481. try
  482. {
  483. using (StreamWriter sw = new StreamWriter(path))
  484. {
  485. Type t = obja.GetType();
  486. XmlSerializer serializer = new XmlSerializer(obja.GetType());
  487. serializer.Serialize(sw, obja);
  488. sw.Close();
  489. }
  490. }
  491. catch (Exception e)
  492. {
  493. e.ToString();
  494. }
  495. }
  496. /// <summary>
  497. /// XMLs the configuration reader.
  498. /// </summary>
  499. /// <param name="filePath">The file path.</param>
  500. /// <param name="type">The type.</param>
  501. /// <returns>System.Object.</returns>
  502. public static object XmlConfigReader(string filePath, Type type)
  503. {
  504. object result = null;
  505. try
  506. {
  507. if (File.Exists(filePath))
  508. {
  509. using (StreamReader reader = new StreamReader(filePath))
  510. {
  511. XmlSerializer xmlSerializer = new XmlSerializer(type);
  512. result = xmlSerializer.Deserialize(reader);
  513. }
  514. }
  515. return result;
  516. }
  517. catch (Exception e)
  518. {
  519. return e;
  520. }
  521. }
  522. }
  523. }