对象与XML之间互相转化的一个基类

在实际开发过程中经常需要把一个对象保存到XML中,同时也需要把保存的XML转化为对象。随便代码很简单。是人都会。但经常写着这样的重复代码就想能不能有什么样的方法可以少写点代码呢。能不写当然最好了。经过摸索就写了下面这个小玩意

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace KSoft.ApplicationCommunication
{
    
public class XMLObject
    {
        
internal void ReadXml(string xml)
        {
            
object obj = null;
            StringReader reader 
= new StringReader(xml);
            
try
            {
                System.Xml.Serialization.XmlSerializer ser 
= new XmlSerializer(this.GetType());
                obj 
= ser.Deserialize(reader);
            }
            
finally { reader.Close(); }

            
//给This的属性赋值
            System.Reflection.PropertyInfo[] propertyThis = this.GetType().GetProperties();
            System.Reflection.PropertyInfo[] propertyObj 
= obj.GetType().GetProperties();
            
for (int i = 0; i < propertyThis.Length; i++)
            {
                propertyThis[i].SetValue(
this, propertyObj[i].GetValue(obj, null), null);
            }  
        }

        
public string ToXML()
        {
            System.IO.StringWriter writer 
= new System.IO.StringWriter();
            System.Xml.Serialization.XmlSerializer ser 
= new XmlSerializer(this.GetType());
            ser.Serialize(writer, 
this);
            
string strRet = writer.ToString();
            writer.Close();
            
return strRet;
        }
    }
}
posted @ 2009-02-22 21:03  君无忌  阅读(418)  评论(0)    收藏  举报