例如,我们需要读取users.xml中的数据,一种比较笨的方法是,将users.xml直接拷到pda上,但是这种方法并不通用,我们可以借鉴透明按钮的方法,把他作为嵌入的资源,这个所谓的嵌入的资源就是当部署的时候,会直接部署到pda上,不需要拷贝进去。
=======================================
第一种方法,我们直接拷到pda上:
=========================================
Cursor.Current = Cursors.WaitCursor;
DataSet ds = new DataSet();
ds.ReadXml((@"/users.xml"));//这时我们把users.xml存放在/下
int count = ds.Tables["user"].Rows.Count; //看表中有多少个user
operateData.createFile("MobileLawEn.sdf");
if (ds != null && count > 0)
{
checkTableExistance("users");
SqlCeConnection conn = new SqlCeConnection(operateData.connStr);
SqlCeCommand cmd = new SqlCeCommand(
"create table users(username nvarchar(20),password nvarchar(20),deptid int,constraint p_key primary key(username,deptid))", conn);
conn.Open();
int rst = cmd.ExecuteNonQuery();
Cursor.Current = Cursors.Default;
for (int i = 0; i < count; i++)
{
string name = ds.Tables["user"].Rows[i]["username"].ToString();
//读取第i个user中的用户名
string password = ds.Tables["user"].Rows[i]["password"].ToString();
string deptid = ds.Tables["user"].Rows[i]["deptid"].ToString();
string sql = "insert into users (username,password,deptid) values ('" + name + "','" + password + "'," + deptid + ")";
SqlCeCommand comm = new SqlCeCommand(sql, conn);
comm.ExecuteNonQuery();
}
conn.Close();
Cursor.Current = Cursors.Default;
============================================
第二种方法:我们将xml文件作为嵌入的资源:
=============================================
首先嵌入:
Cursor.Current = Cursors.WaitCursor;
DataSet ds = null;
ds = new DataSet();
System.IO.Stream strm = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MobileLawEn.xml.users.xml");
//GetManifestResourceStream是用来加载制定的资源。
ds.ReadXml(strm, System.Data.XmlReadMode.InferSchema);
//System.Data.XmlReadMode.InferSchema用来设置这种模式:
InferSchema |
忽略任何嵌入式架构,并从 XML 数据推断架构 |
int count = ds.Tables["user"].Rows.Count; //看表中有多少个user
operateData.createFile("MobileLawEn.sdf");
if (ds != null && count > 0)
{
checkTableExistance("users");
SqlCeConnection conn = new SqlCeConnection(operateData.connStr);
SqlCeCommand cmd = new SqlCeCommand(
"create table users(username nvarchar(20),password nvarchar(20),deptid int,constraint p_key primary key(username,deptid))", conn);
conn.Open();
int rst = cmd.ExecuteNonQuery();
Cursor.Current = Cursors.Default;
for (int i = 0; i < count; i++)
{
string name = ds.Tables["user"].Rows[i]["username"].ToString();//读取第i个user中的用户名
string password = ds.Tables["user"].Rows[i]["password"].ToString();
//读取第i个user中的密码
string deptid = ds.Tables["user"].Rows[i]["deptid"].ToString();
string sql = "insert into users (username,password,deptid) values ('" + name + "','" + password + "'," + deptid + ")";
SqlCeCommand comm = new SqlCeCommand(sql, conn);
comm.ExecuteNonQuery();
}
conn.Close();
Cursor.Current = Cursors.Default;