I have a typed dataset in my project and i need to import data from XML. I managed to import data to Tables collection in my typed dataset, but I need to have access to the data via Annotations - properties named the same as tables in my dataset.
this.ConfigDataSet.Reset();
this.ConfigDataSet.ReadXml(FileName,XmlReadMode.ReadSchema);
this.ConfigDataSet.AcceptChanges();
Do I have to copy data field by field?
I have something like this:
this.ConfigDataSet.Tables["TabName"].Rows.Count //returns 3
this.ConfigDataSet.TabName.Rows.Count //returns 0
I write xml like this:
this.ConfigDataSet.AcceptChanges();
this.ConfigDataSet.WriteXml(FileName,XmlWriteMode.WriteSchema);
Check this out:
class Program
{
static void Main(string[] args)
{
DataTable tbl = GetTable();
DataSet ds = new DataSet();
ds.Tables.Add(tbl);
//file path to write xml file
ds.WriteXml("test.xml");
DataSet ds2 = new DataSet();
//file path to read xml file
ds2.ReadXml("test.xml");
}
static DataTable GetTable()
{
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
return table;
}
}
Check here for DataSet.WriteXml()
and here for DataSet.ReadXml()
;
Solution:
WriteXml:
ConfigDataSet.WriteXml(FileName);
ReadXml:
using (DataSet ds = new DataSet())
{
ds.ReadXml(FileName);
ConfigDataSet.Load(ds.Tables[0].CreateDataReader(), LoadOption.OverwriteChanges, ConfigDataSet.TableName1);
ConfigDataSet.Load(ds.Tables[1].CreateDataReader(), LoadOption.OverwriteChanges, ConfigDataSet.TableName2);
ConfigDataSet.Load(ds.Tables[2].CreateDataReader(), LoadOption.OverwriteChanges, ConfigDataSet.TableName3);
ConfigDataSet.Load(ds.Tables[3].CreateDataReader(), LoadOption.OverwriteChanges, ConfigDataSet.TableName4);
}
It is required to load each table separately, but it is better than load each field row by row.
Regards, Kuba.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.