XmlHelper.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. namespace Bowin.Common.XML
  11. {
  12. public class XmlHelper
  13. {
  14. private static Regex rgxRoot = new Regex("<(\\w+?)[ >]", RegexOptions.Compiled);
  15. private static Regex rgxCid = new Regex("RE\\w+", RegexOptions.IgnoreCase);
  16. private static ConcurrentDictionary<string, XmlSerializer> cache = new ConcurrentDictionary<string, XmlSerializer>();
  17. // <summary>
  18. /// XML序列化成实体类
  19. /// </summary>
  20. /// <typeparam name="T">序列化的实体类</typeparam>
  21. /// <param name="strBody">XML格式的字符串</param>
  22. /// <returns>返回序列化后的类</returns>
  23. public static T Parse<T>(string strBody)
  24. {
  25. string rootTagName = GetRoot(strBody);
  26. string strCommand = GetCommand(strBody);
  27. XmlSerializer serizaier = cache[strCommand];
  28. if (serizaier == null)
  29. {
  30. XmlAttributes rootAttrs = new XmlAttributes();
  31. rootAttrs.XmlRoot = new XmlRootAttribute(rootTagName);
  32. XmlAttributeOverrides attrOvrs = new XmlAttributeOverrides();
  33. attrOvrs.Add(typeof(T), rootAttrs);
  34. serizaier = new XmlSerializer(typeof(T), attrOvrs);
  35. //serizaier = new XmlSerializer(typeof(T));
  36. if (!cache.ContainsKey(strCommand))
  37. {
  38. cache[strCommand] = serizaier;
  39. }
  40. }
  41. object obj = null;
  42. using (Stream stream = new MemoryStream(Encoding.GetEncoding("GB2312").GetBytes(strBody)))
  43. {
  44. obj = serizaier.Deserialize(stream);
  45. }
  46. return (T)obj;
  47. }
  48. /// <summary>
  49. /// 取得消息命令头
  50. /// </summary>
  51. /// <param name="strXml">要检查的XML字符串</param>
  52. /// <returns>返回找到的命令头</returns>
  53. private static string GetCommand(string strXml)
  54. {
  55. Match match = rgxCid.Match(strXml);
  56. if (match.Success)
  57. return match.Groups[0].ToString();
  58. else
  59. throw new Exception("Invalid XML response format!");
  60. }
  61. /// <summary>
  62. /// 获取XML根节点名称
  63. /// </summary>
  64. /// <param name="strBody"></param>
  65. /// <returns></returns>
  66. private static string GetRoot(string strBody)
  67. {
  68. Match match = rgxRoot.Match(strBody);
  69. if (match.Success)
  70. return match.Groups[1].ToString();
  71. else
  72. throw new Exception("Invalid XML response format!");
  73. }
  74. }
  75. }