1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- 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<string, XmlSerializer> cache = new ConcurrentDictionary<string, XmlSerializer>();
- public static string ToXml<T>(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();
- }
- // <summary>
- /// XML序列化成实体类
- /// </summary>
- /// <typeparam name="T">序列化的实体类</typeparam>
- /// <param name="strBody">XML格式的字符串</param>
- /// <returns>返回序列化后的类</returns>
- public static T Parse<T>(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;
- }
- /// <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!");
- }
- }
- }
|