代码改变世界

DataSet 操作 XML 文件的方法

2013-03-22 00:05  java20130722  阅读(232)  评论(0编辑  收藏  举报
class Program
    {
        static void Main(string[] args)
        {
            DataSet ds = new DataSet();
            DataTable dt = null;

            //向DataSet中新增两个DataTable
            dt = SetDataTable(3, 4);
            dt.TableName = "Table1";
            ds.Tables.Add(dt);
            dt = SetDataTable(2, 3);
            dt.TableName = "Table2";
            ds.Tables.Add(dt);            

            //写入到test.xml文件中
            ds.WriteXml("test.xml");

            ds.Clear();

            //从est.xml文件中读到DataSet中
            ds.ReadXml("test.xml");

            //打印出读取到的内容
            foreach (DataTable dtTab in ds.Tables)
            {
                Console.WriteLine("\n表名:{0}", dtTab.TableName.ToString());
                foreach (DataRow dtRow in dtTab.Rows)
                {
                    for (int i = 0; i < dtTab.Columns.Count; i++)
                    {
                        Console.Write("{0}, ", dtRow[i].ToString());
                    }
                    Console.WriteLine();
                }
            }
           
        }

        /// <summary>
        /// 设置一个DataTable
        /// </summary>
        /// <param name="cntCols">DataTable的列数</param>
        /// <param name="cntRows">DataTable的行数</param>
        /// <returns></returns>
        static private DataTable SetDataTable(int cntCols, int cntRows)
        {
            DataTable dt = new DataTable();
            DataRow dr = null;
            DataColumn dc = null;

            for (int i = 0; i < cntCols; i++)
            {
                dc = new DataColumn("col"+i.ToString(), System.Type.GetType("System.String"));
                dt.Columns.Add(dc);
            }

            for (int i = 0; i < cntRows; i++ )
            {
                dr = dt.NewRow();
                for (int j = 0; j < cntCols; j++)
                {
                    dr[j] = j.ToString();
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
    }