把datatable保存为xml,再读取xml转化为datatable
DataTable dt = new DataTable("dt", "http://baidu.com"); dt.Prefix = "xs";//前缀 dt.Columns.Add("id"); dt.Columns.Add("name"); DataRow dr = dt.NewRow(); dr["id"] = "123"; dr["Name"] = "xs"; dt.Rows.Add(dr); DataRow dr1 = dt.NewRow(); dr1["id"] = "456"; dr1["Name"] = "xsdc"; dt.Rows.Add(dr1); //dt.WriteXml("C:\\2.xml");//此方法保存的xml只是datatable,读取时会失败 dt.WriteXml("C:\\1.xml", XmlWriteMode.WriteSchema);//会在xnl中自动生成新的dataset DataTable dt1 = new DataTable("dt"); dt1.ReadXml(@"C:\\1.xml");
1.xml
<?xml version="1.0" standalone="yes"?> <NewDataSet xmlns="http://baidu.com"> <xs:schema id="NewDataSet" targetNamespace="http://baidu.com" xmlns:mstns="http://baidu.com" xmlns="http://baidu.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified"> <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="http_x003A__x002F__x002F_baidu.com_x003A_dt" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="dt" msdata:Prefix="xs"> <xs:complexType> <xs:sequence> <xs:element name="id" type="xs:string" minOccurs="0" /> <xs:element name="name" type="xs:string" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <xs:dt xmlns:xs="http://baidu.com"> <id>123</id> <name>xs</name> </xs:dt> <xs:dt xmlns:xs="http://baidu.com"> <id>456</id> <name>xsdc</name> </xs:dt> </NewDataSet>
2.xml
<?xml version="1.0" standalone="yes"?> <xs:DocumentElement xmlns:xs="http://baidu.com"> <xs:dt> <id xmlns="http://baidu.com">123</id> <name xmlns="http://baidu.com">xs</name> </xs:dt> <xs:dt> <id xmlns="http://baidu.com">456</id> <name xmlns="http://baidu.com">xsdc</name> </xs:dt> </xs:DocumentElement>