zoukankan      html  css  js  c++  java
  • XML响应通用解释器 上海

     /// <summary>
        /// XML响应通用解释器。
        /// </summary>
        public class XmlParser<T> : IParser<T> where T : Response
        {
            private static Regex regex = new Regex("<(http://www.cnblogs.com/luozhai714/admin/file://w/+?)[ >]", RegexOptions.Compiled);
            private static Hashtable parsers = Hashtable.Synchronized(new Hashtable());

            #region IParser<T> Members

            public T Parse(string body)
            {
                string rootTagName = GetRootElement(body);
                XmlSerializer serializer = parsers[rootTagName] as XmlSerializer;
                if (serializer == null)
                {
                    XmlAttributes rootAttrs = new XmlAttributes();
                    rootAttrs.XmlRoot = new XmlRootAttribute(rootTagName);

                    XmlAttributeOverrides attrOvrs = new XmlAttributeOverrides();
                    attrOvrs.Add(typeof(T), rootAttrs);

                    serializer = new XmlSerializer(typeof(T), attrOvrs);
                    // double check contain
                    if (!parsers.ContainsKey(rootTagName))
                    {
                        parsers.Add(rootTagName, serializer);
                    }
                }

                object obj = null;
                using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(body)))
                {
                    obj = serializer.Deserialize(stream);
                }

                T rsp = (T)obj;
                if (rsp != null)
                {
                    rsp.Body = body;
                }
                return rsp;
            }

            #endregion

            /// <summary>
            /// 获取XML响应的根节点名称
            /// </summary>
            private string GetRootElement(string body)
            {
                Match match = regex.Match(body);
                if (match.Success)
                {
                    return match.Groups[1].ToString();
                }
                else
                {
                    throw new MyException("Invalid XML response format!");
                }
            }
        }

  • 相关阅读:
    不测的秘密:精准测试之路----读书笔记(第二章)
    如何使用for循环连续的实例化多个对象!
    java如何在一个有序的数组类插入一个数!
    webstrom 常用快捷键
    如何使Label带有链接??此法感觉有点取巧!!!
    System.DateTime的一些格式
    如何解决”无法将类型为“System.DateTime”的对象强制转换为类型“System.String”。“
    如何解决“连接未关闭。 连接的当前状态为打开”问题
    c语言中 %p的含义
    什么情况下用递归?
  • 原文地址:https://www.cnblogs.com/luozhai714/p/2174497.html
Copyright © 2011-2022 走看看