AliyunXmlParser.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.Xml.Serialization;
  7. using Top.Api;
  8. namespace Aliyun.Api.Parser
  9. {
  10. /// <summary>
  11. /// TOP XML响应通用解释器。
  12. /// </summary>
  13. public class AliyunXmlParser : IAliyunParser
  14. {
  15. private static readonly Regex regex = new Regex("<(\\w+?)[ >]", RegexOptions.Compiled);
  16. private static readonly object writeLock = new object();
  17. private static readonly Dictionary<string, XmlSerializer> parsers = new Dictionary<string, XmlSerializer>();
  18. #region ITopParser Members
  19. public T Parse<T>(string body) where T : AliyunResponse
  20. {
  21. Type type = typeof(T);
  22. string rootTagName = GetRootElement(body);
  23. string key = type.FullName;
  24. if (Constants.ERROR_RESPONSE.Equals(rootTagName))
  25. {
  26. key += ("_" + Constants.ERROR_RESPONSE);
  27. }
  28. XmlSerializer serializer = null;
  29. bool incl = parsers.TryGetValue(key, out serializer);
  30. if (!incl || serializer == null)
  31. {
  32. XmlAttributes rootAttrs = new XmlAttributes();
  33. rootAttrs.XmlRoot = new XmlRootAttribute(rootTagName);
  34. XmlAttributeOverrides attrOvrs = new XmlAttributeOverrides();
  35. attrOvrs.Add(type, rootAttrs);
  36. serializer = new XmlSerializer(type, attrOvrs);
  37. lock (writeLock)
  38. {
  39. parsers[key] = serializer;
  40. }
  41. }
  42. object obj = null;
  43. using (System.IO.Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(body)))
  44. {
  45. obj = serializer.Deserialize(stream);
  46. }
  47. T rsp = (T)obj;
  48. if (rsp != null)
  49. {
  50. rsp.Body = body;
  51. }
  52. return rsp;
  53. }
  54. #endregion
  55. /// <summary>
  56. /// 获取XML响应的根节点名称
  57. /// </summary>
  58. private string GetRootElement(string body)
  59. {
  60. Match match = regex.Match(body);
  61. if (match.Success)
  62. {
  63. return match.Groups[1].ToString();
  64. }
  65. else
  66. {
  67. throw new TopException("Invalid XML response format!");
  68. }
  69. }
  70. }
  71. }