1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Xml.Serialization;
- namespace SiwiFms.Helper
- {
- public class XmlHelper
- {
- /// <summary>
- /// xml字符串转对象
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="xmlStr"></param>
- /// <returns></returns>
- public static T DeserializeXmlStr<T>(string xmlStr) {
- if (string.IsNullOrWhiteSpace(xmlStr)) return default(T);
- try
- {
- using (StringReader sr = new StringReader(xmlStr))
- {
- XmlSerializer xs = new XmlSerializer(typeof(T));
- return (T)xs.Deserialize(sr);
- }
- }
- catch (Exception ex) {
- Console.WriteLine(ex.Message);
- return default(T);
- }
- }
- /// <summary>
- /// xml序列化
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static string SerializeXmlStr(object obj) {
- if (obj == null) return string.Empty;
- MemoryStream stream = new MemoryStream();
- StreamReader sr = null;
- try
- {
- XmlSerializer xs = new XmlSerializer(obj.GetType());
- xs.Serialize(stream, obj);
- stream.Position = 0;
- sr = new StreamReader(stream);
- return sr.ReadToEnd();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- return "";
- }
- finally {
- if (sr != null)
- {
- sr.Dispose();
- }
- stream.Dispose();
- }
- }
- }
- }
|