- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Xml.Serialization;
- namespace ConsoleTest
- {
- class Program
- {
- static void Main(string[] args)
- {
- clsTest c = new clsTest();
- c.stringvalue = "rrrrrr";
- string s = ToXml<clsTest>(c);
- clsTest c1 = FromXml <clsTest>(s);
- c1.ToString();
- }
- static public string ToXml<T>(T c) where T : class
- {
- string strXml = string.Empty;
- try
- {
- MemoryStream ms = new MemoryStream();
- XmlSerializer xml = new XmlSerializer(typeof(T));
- xml.Serialize(ms, c);
- byte[] arr = ms.ToArray();
- strXml = Encoding.UTF8.GetString(arr, 0, arr.Length);
- return strXml;
- }
- catch (Exception ex)
- {
- throw;
- }
- }
- /// <summary>
- ///从Xml字符串读取属性值
- /// </summary>
- static public T FromXml<T>(string XMLString) where T : class
- {
- MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XMLString));
- XmlSerializer xml = new XmlSerializer(typeof(clsTest));
- T c = xml.Deserialize(ms) as T;
- return c;
- }
- }
- public class clsTest
- {
- public int intvalue = 0;
- public string stringvalue = "";
- public DateTime dt = DateTime.Now;
- public override string ToString()
- {
- Console.WriteLine(intvalue);
- Console.WriteLine(stringvalue);
- Console.WriteLine(dt);
- return base.ToString();
- }
- }
- }
本文转自cnn23711151CTO博客,原文链接:http://blog.51cto.com/cnn237111/603220 ,如需转载请自行联系原作者