123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- 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<string, XmlSerializer> cache = new ConcurrentDictionary<string, XmlSerializer>();
- // <summary>
- /// XML序列化成实体类
- /// </summary>
- /// <typeparam name="T">序列化的实体类</typeparam>
- /// <param name="strBody">XML格式的字符串</param>
- /// <returns>返回序列化后的类</returns>
- public static T Parse<T>(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;
- }
- /// <summary>
- /// 取得消息命令头
- /// </summary>
- /// <param name="strXml">要检查的XML字符串</param>
- /// <returns>返回找到的命令头</returns>
- 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!");
- }
- /// <summary>
- /// 获取XML根节点名称
- /// </summary>
- /// <param name="strBody"></param>
- /// <returns></returns>
- 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!");
- }
- }
- }
|