asp.net xml序列化与反序列化

 更新时间:2008年08月13日 10:44:41   作者:  
在.NET下有一种技术叫做对象序列化,它可以将对象序列化为二进制文件、XML文件、SOAP文件,这样, 使用经过序列化的流进行传输效率就得到了大大的提升。


反序列化就是读取xml文件并将其值自动匹配给类中的公有属性或方法或字段,也就是上面的逆操作。 C#复制代码
webinfo info = new webinfo();    

//用webinfo这个类造一个XmlSerializer    
XmlSerializer ser = new XmlSerializer(typeof(webinfo));    

string path = Server.MapPath("webinfo.xml");    

//Stream用于提供字节序列的一般视图,这里将打开一个xml文件    
Stream file = new FileStream(path, FileMode.Open, FileAccess.Read);    

//把字节序列(stream)反序列化   
info = (webinfo)ser.Deserialize(file);    

Response.Write("站长:" + info.userName + "<br>");    
Response.Write("站名:" + info.webName + "<br>");    
Response.Write("域名:" + info.webUrl);   

输出结果:


为了更好的封装和保护类的成员和方法,我们将类webinfo改写成: 折叠展开C#复制代码
public class webinfo    
{    
    //站长    
    private string userName;    
    public string UserName    
    {    
        get   
        {    
            return userName;    
        }    
        set   
        {    
            userName = value;    
        }    
    }    

    //站名    
    private string webName;    
    public string WebName    
    {    
        get   
        {    
            return webName;    
        }    
        set   
        {    
            webName = value;    
        }    
    }    

    //域名    
    private string webUrl;    
    public string WebUrl    
    {    
        get   
        {    
            return webUrl;    
        }    
        set   
        {    
            webUrl = value;    
        }    
    }    
}   
使用时区别仅仅是小小的改动具体的可以看下面: C#复制代码
webinfo info = new webinfo();        
info.userName = "脚本之家";-->info.UserName = "脚本之家";    
info.webName = "脚本"; -->info.WebName  = "脚本";       
info.webUrl = "https://www.jb51.net";  -->//自己写吧  

相关文章

最新评论