XmlHelper.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Xml.Serialization;
  7. using System.Text.RegularExpressions;
  8. using System.Collections;
  9. using System.Collections.Concurrent;
  10. using System.Xml;
  11. namespace Bowin.Common.XML
  12. {
  13. public static class XmlHelper
  14. {
  15. private static Regex rgxRoot = new Regex("<(\\w+?)[ >]", RegexOptions.Compiled);
  16. private static Regex rgxCid = new Regex("RE\\w+", RegexOptions.IgnoreCase);
  17. private static ConcurrentDictionary<string, XmlSerializer> cache = new ConcurrentDictionary<string, XmlSerializer>();
  18. public static string ToXml<T>(this T entity, Encoding encoding = null) where T : class
  19. {
  20. if (encoding == null)
  21. {
  22. encoding = UTF8Encoding.UTF8;
  23. }
  24. var type = entity.GetType();
  25. XmlSerializer xs = new XmlSerializer(type);
  26. StringBuilder stb = new StringBuilder();
  27. XmlWriter xw = XmlWriter.Create(stb, new XmlWriterSettings() { Encoding = encoding });
  28. xs.Serialize(xw, entity);
  29. return stb.ToString();
  30. }
  31. // <summary>
  32. /// XML序列化成实体类
  33. /// </summary>
  34. /// <typeparam name="T">序列化的实体类</typeparam>
  35. /// <param name="strBody">XML格式的字符串</param>
  36. /// <returns>返回序列化后的类</returns>
  37. public static T Parse<T>(string strBody, Encoding encoding = null)
  38. {
  39. if (encoding == null)
  40. {
  41. encoding = UTF8Encoding.UTF8;
  42. }
  43. var type = typeof(T);
  44. XmlSerializer serizaier = new XmlSerializer(type);
  45. object obj = null;
  46. using (Stream stream = new MemoryStream(encoding.GetBytes(strBody)))
  47. {
  48. obj = serizaier.Deserialize(stream);
  49. }
  50. return (T)obj;
  51. }
  52. /// <summary>
  53. /// 取得消息命令头
  54. /// </summary>
  55. /// <param name="strXml">要检查的XML字符串</param>
  56. /// <returns>返回找到的命令头</returns>
  57. private static string GetCommand(string strXml)
  58. {
  59. Match match = rgxCid.Match(strXml);
  60. if (match.Success)
  61. return match.Groups[0].ToString();
  62. else
  63. throw new Exception("Invalid XML response format!");
  64. }
  65. /// <summary>
  66. /// 获取XML根节点名称
  67. /// </summary>
  68. /// <param name="strBody"></param>
  69. /// <returns></returns>
  70. private static string GetRoot(string strBody)
  71. {
  72. Match match = rgxRoot.Match(strBody);
  73. if (match.Success)
  74. return match.Groups[1].ToString();
  75. else
  76. throw new Exception("Invalid XML response format!");
  77. }
  78. }
  79. }