using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml.Serialization; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Concurrent; namespace Bowin.Common.XML { public class XmlHelper { private static Regex rgxRoot = new Regex("<(\\w+?)[ >]", RegexOptions.Compiled); private static Regex rgxCid = new Regex("RE\\w+", RegexOptions.IgnoreCase); private static ConcurrentDictionary cache = new ConcurrentDictionary(); // /// XML序列化成实体类 /// /// 序列化的实体类 /// XML格式的字符串 /// 返回序列化后的类 public static T Parse(string strBody) { string rootTagName = GetRoot(strBody); string strCommand = GetCommand(strBody); XmlSerializer serizaier = cache[strCommand]; if (serizaier == null) { XmlAttributes rootAttrs = new XmlAttributes(); rootAttrs.XmlRoot = new XmlRootAttribute(rootTagName); XmlAttributeOverrides attrOvrs = new XmlAttributeOverrides(); attrOvrs.Add(typeof(T), rootAttrs); serizaier = new XmlSerializer(typeof(T), attrOvrs); //serizaier = new XmlSerializer(typeof(T)); if (!cache.ContainsKey(strCommand)) { cache[strCommand] = serizaier; } } object obj = null; using (Stream stream = new MemoryStream(Encoding.GetEncoding("GB2312").GetBytes(strBody))) { obj = serizaier.Deserialize(stream); } return (T)obj; } /// /// 取得消息命令头 /// /// 要检查的XML字符串 /// 返回找到的命令头 private static string GetCommand(string strXml) { Match match = rgxCid.Match(strXml); if (match.Success) return match.Groups[0].ToString(); else throw new Exception("Invalid XML response format!"); } /// /// 获取XML根节点名称 /// /// /// private static string GetRoot(string strBody) { Match match = rgxRoot.Match(strBody); if (match.Success) return match.Groups[1].ToString(); else throw new Exception("Invalid XML response format!"); } } }