DataSet与Xml之间的转换
DataSet转化为Xml,Xml转化为DataSet,Ado.net中使用方法DataSet.WriteXml()和DataSet.ReadXml(),由于有多个重载方法,所以这里有多条路径可以实现,可谓条条大道通罗马。这里我就把所有的用法来尝试下,希望给大家有个借鉴作用。 因为DataSet.ReadXml()和DataSet.WriteXml()共8种重载方法,前四种是不带架构的,后四种带架构。这里举出带架构的4种方法。 /// <summary> /// DataSet和Xml之间的转换 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DsAndXml_Click(object sender, EventArgs e) { //自定义一个DataSet,里面有一列a,一行值为"hello world!",Xml数据从这个数据集中来读取 DataSet dsWrite = new DataSet(); DataTable dt = new DataTable(); dt.Columns.Add("a", typeof(string)); DataRow dr = dt.NewRow(); dr[0] = "hello world!"; dt.Rows.Add(dr); dsWrite.Tables.Add(dt); //自定义一个DataSet用来从xml中读取数据 DataSet dsRead = new DataSet(); int k = Convert.ToInt32(this.textBox1.Text.ToString());//第几种重载 switch(k) { //第一种使用stream case 1: //创建文件流,将DataSet中的数据写入文件流中 Stream stream = new FileStream(@System.AppDomain.CurrentDomain.BaseDirectory.ToString()+"Test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); //dsWrite.WriteXml(stream);//不带架构 dsWrite.WriteXml(stream, XmlWriteMode.WriteSchema);//将架构一起写入文件流 stream.Close(); //从文件里读取 dsRead.ReadXml(@System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "Test.txt"); break; //第二种使用FileName case 2: //写出 dsWrite.WriteXml(@System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "Test.txt"); //读入 dsRead.ReadXml(@System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "Test.txt"); break; //第三种使用XmlTextWriter case 3: //写出 StringBuilder s1 = new StringBuilder(); TextWriter tw1 = new StringWriter(s1); System.Xml.XmlTextWriter xtw1= new System.Xml.XmlTextWriter(tw1); dsWrite.WriteXml(xtw1,XmlWriteMode.WriteSchema); string xml1 = s1.ToString(); //读入 TextReader tr1 = new StringReader(xml1); dsRead.ReadXml(tr1,XmlReadMode.ReadSchema); //System.Xml.XmlReader xr = System.Xml.XmlReader.Create(tr1); //dsRead.ReadXml(xr); break; //第四种使用TextReader、TextWriter case 4: //DataSet转化为xml StringBuilder s = new StringBuilder(); TextWriter tw = new StringWriter(s); dsWrite.WriteXml(tw, XmlWriteMode.WriteSchema); string xml = s.ToString(); //xml转化为DataSet TextReader tr = new StringReader(xml); dsRead.ReadXml(tr,XmlReadMode.ReadSchema); break; default: break; } }