XML文档使用越来越普遍,我们常会把一些系统设置等文件用config或XML文档存文在程序目录下。.Net的串行化数据是一个很令人心动的技术,可以很方便地读取一定格式或保存成文件。下面做个简单了练习,对XML串行化作些初步了解。(注:我是在WINDOWS应用程序上做的练习,因怕建立ASP.NETA工程麻烦,下面一大堆东西。其实除了路径外,程序写法基本一致)。
先编写一个需要串行化的类,该类是设置一个操作权限的设置文件
using System;
namespace Hellosea.WinModule.Account.Configuration
{
/// <summary>
/// OperatePermissionSettings 的摘要说明。
/// </summary>
public class OperatePermissionSettings
{
public OperatePermissionSettings()
{ }
public int SystemManage_Login; // 允许进入管理页面,为各管理角色所拥用的许可
public int SystemManage_SystemSetting; // 可以进行系统参数、安全等设置的许可
public int UserManage_Enter; // 进入用户管理页面的许可
public int UserManage_PurviewAssign; // 可以分配或收回用户角色、许可等的权限
public int UserManage_UserDelete; // 可以中止用户帐号的许可
public int UserManage_UserEdit; // 可以编辑用户信息的许可
}
}
串行化该类,并保存文件:
private void button1_Click(object sender, System.EventArgs e)
{
// 建立操作权限类
OperatePermissionSettings settings = new OperatePermissionSettings();
settings.SystemManage_Login = 1;
settings.SystemManage_SystemSetting = 2;
settings.UserManage_Enter = 3;
settings.UserManage_PurviewAssign = 4;
settings.UserManage_UserEdit = 5;
settings.UserManage_UserDelete = 6;
// 文件流
string filePath = Application.StartupPath + "\\OperatePermission.Config";
FileStream fs = new FileStream(filePath, FileMode.Create);
// 串行化数据
XmlSerializer serializer = new XmlSerializer(typeof(OperatePermissionSettings));
serializer.Serialize(fs, settings);
// 关闭文件流
fs.Close();
}
反串行化,从文件中读取数据
private void button2_Click(object sender, System.EventArgs e)
{
OperatePermissionSettings settings = new OperatePermissionSettings();
// 文件流
string filePath = Application.StartupPath + "\\OperatePermission.Config";
FileStream fs = new FileStream(filePath, FileMode.Open);
// 反串行化数据
XmlSerializer serializer = new XmlSerializer(typeof(OperatePermissionSettings));
settings = (OperatePermissionSettings)serializer.Deserialize(fs);
// 关闭文件流
fs.Close();
textBox1.Text = settings.SystemManage_Login.ToString();
textBox2.Text = settings.SystemManage_SystemSetting.ToString();
textBox3.Text = settings.UserManage_Enter.ToString();
textBox4.Text = settings.UserManage_PurviewAssign.ToString();
textBox5.Text = settings.UserManage_UserEdit.ToString();
textBox6.Text = settings.UserManage_UserDelete.ToString();
}
当然需要用到二个命名空间
using System.IO;
using System.Xml.Serialization;
另外OperatePermission.Config文档的结构如下:
<?xml version="1.0"?>
<OperatePermissionSettings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SystemManage_Login>1</SystemManage_Login>
<SystemManage_SystemSetting>2</SystemManage_SystemSetting>
<UserManage_Enter>3</UserManage_Enter>
<UserManage_PurviewAssign>4</UserManage_PurviewAssign>
<UserM