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!");
                }
            }
        }

  • 相关阅读:
    Qt Qwt之坐标轴移动
    Lnux 16.04 VM下安装与汉化
    【学习笔记】开源日志记录工具log4j使用方法
    【学习笔记】关于DOM4J:使用DOM4J解析XML文档
    DOM的概念和简单应用:使用DOM解析XML数据
    初识Socket通信:基于TCP和UDP协议学习网络编程
    java 中的Scanner
    跟着前辈学编程
    集合应用案例:编写程序实现学生信息管理系统的录入登录
    简单Java程序向实用程序的过度:二进制文件的读写
  • 原文地址:https://www.cnblogs.com/luozhai714/p/2174497.html
Copyright © 2011-2022 走看看