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; using System.Xml; namespace Bowin.Common.XML { public static 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(); public static string ToXml(this T entity, Encoding encoding = null) where T : class { if (encoding == null) { encoding = UTF8Encoding.UTF8; } var type = entity.GetType(); XmlSerializer xs = new XmlSerializer(type); StringBuilder stb = new StringBuilder(); XmlWriter xw = XmlWriter.Create(stb, new XmlWriterSettings() { Encoding = encoding }); xs.Serialize(xw, entity); return stb.ToString(); } // /// XML序列化成实体类 /// /// 序列化的实体类 /// XML格式的字符串 /// 返回序列化后的类 public static T Parse(string strBody, Encoding encoding = null) { if (encoding == null) { encoding = UTF8Encoding.UTF8; } var type = typeof(T); XmlSerializer serizaier = new XmlSerializer(type); object obj = null; using (Stream stream = new MemoryStream(encoding.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!"); } } }