这段代码,我写一次,就要上网找一次,决定把他们记下来!

引用
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

  public static String SerializeToXml<T>(T arg)
    
{
        XmlSerializer serializer 
= new XmlSerializer(arg.GetType());

        StringBuilder sb 
= new StringBuilder();
        XmlWriter writer 
= new XmlTextWriter(new StringWriter(sb));

        serializer.Serialize(writer, arg);
        writer.Close();

        
return sb.ToString();
    }


    
/// <summary>
    
/// 从一个XML字符串中建立对像
    
/// </summary>
    
/// <typeparam name="T"></typeparam>
    
/// <param name="xml"></param>
    
/// <returns></returns>

    public static T CreateFromXml<T>(String xml) where T : class
    
{
        XmlReader reader 
= new XmlTextReader(new StringReader(xml));
        
try
        
{
            XmlSerializer serializer 
= new XmlSerializer(typeof(T));

            Object theObject 
= serializer.Deserialize(reader);
            reader.Close();
            reader 
= null;

            
return (T)theObject;
        }

        
catch
        
{
            
if (reader != null)
            
{
                reader.Close();
                reader 
= null;
            }

            
return default(T);
        }


    }

posted on 2006-11-03 14:58  Yunanw  阅读(272)  评论(1编辑  收藏  举报