QimenXmlParser.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using Qimen.Api;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Xml.Serialization;
  8. using Top.Api;
  9. using Top.Api.Parser;
  10. namespace QimenCloud.Api.Parser
  11. {
  12. /// <summary>
  13. /// 奇门XML响应通用解释器。
  14. /// </summary>
  15. /// <typeparam name="T"></typeparam>
  16. public class QimenXmlParser<T> : ITopParser<T> where T : QimenResponse
  17. {
  18. private static readonly ReaderWriterLock rwLock = new ReaderWriterLock();
  19. private static readonly Dictionary<string, XmlSerializer> parsers = new Dictionary<string, XmlSerializer>();
  20. public T Parse(string body)
  21. {
  22. Type type = typeof(T);
  23. return Parse(body, type);
  24. }
  25. public T Parse(string body, Type type)
  26. {
  27. string key = type.FullName;
  28. XmlSerializer serializer = null;
  29. bool incl = false;
  30. rwLock.AcquireReaderLock(50);
  31. try
  32. {
  33. if (rwLock.IsReaderLockHeld)
  34. {
  35. incl = parsers.TryGetValue(key, out serializer);
  36. }
  37. }
  38. finally
  39. {
  40. if (rwLock.IsReaderLockHeld)
  41. {
  42. rwLock.ReleaseReaderLock();
  43. }
  44. }
  45. if (!incl || serializer == null)
  46. {
  47. XmlAttributes rootAttrs = new XmlAttributes();
  48. rootAttrs.XmlRoot = new XmlRootAttribute(Constants.QM_ROOT_TAG_RSP);
  49. XmlAttributeOverrides attrOvrs = new XmlAttributeOverrides();
  50. attrOvrs.Add(type, rootAttrs);
  51. serializer = new XmlSerializer(type, attrOvrs);
  52. rwLock.AcquireWriterLock(50);
  53. try
  54. {
  55. if (rwLock.IsWriterLockHeld)
  56. {
  57. parsers[key] = serializer;
  58. }
  59. }
  60. finally
  61. {
  62. if (rwLock.IsWriterLockHeld)
  63. {
  64. rwLock.ReleaseWriterLock();
  65. }
  66. }
  67. }
  68. object obj = null;
  69. using (System.IO.Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(body)))
  70. {
  71. obj = serializer.Deserialize(stream);
  72. }
  73. T rsp = (T)obj;
  74. if (rsp != null)
  75. {
  76. rsp.Body = body;
  77. }
  78. return rsp;
  79. }
  80. }
  81. }