现在DataTable 存储和读取为xml 非常方便 ,这里帮大家总结下,有些时候,有些复杂的内容就存储为一个xml table ,扔到text字段中去,岂不快哉
DataTable 存储为xml
先建立table , 建立结构 ,建立 writer,就可以了
DataTable dt = new DataTable("MatrixInfo");
DataColumn dc1 = new DataColumn("itemID", Type.GetType("System.String"));
DataColumn dc2 = new DataColumn("itemName", Type.GetType("System.String"));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
for (int i = 0; i < al.Count; i++)
{
DataRow dr = dt.NewRow();
DS_Option dso = (DS_Option)al[i];
dr["itemID"] = dso.ID;
dr["itemName"] = dso.Name;
dt.Rows.Add(dr);
}
string xmlstr;
System.IO.StringWriter writer = new System.IO.StringWriter();
dt.WriteXml(writer);
xmlstr = writer.ToString();
return xmlstr;
DataColumn dc1 = new DataColumn("itemID", Type.GetType("System.String"));
DataColumn dc2 = new DataColumn("itemName", Type.GetType("System.String"));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
for (int i = 0; i < al.Count; i++)
{
DataRow dr = dt.NewRow();
DS_Option dso = (DS_Option)al[i];
dr["itemID"] = dso.ID;
dr["itemName"] = dso.Name;
dt.Rows.Add(dr);
}
string xmlstr;
System.IO.StringWriter writer = new System.IO.StringWriter();
dt.WriteXml(writer);
xmlstr = writer.ToString();
return xmlstr;
读取也类似,但要先建立好打DataTable的结构,不然会出错的
string tbxml = xmlinfo;
DataTable dt = new DataTable("MatrixInfo");
DataColumn dc1 = new DataColumn("itemID", Type.GetType("System.String"));
DataColumn dc2 = new DataColumn("itemName", Type.GetType("System.String"));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
System.IO.StringReader reader = new System.IO.StringReader(tbxml);
dt.ReadXml(reader);
DataTable dt = new DataTable("MatrixInfo");
DataColumn dc1 = new DataColumn("itemID", Type.GetType("System.String"));
DataColumn dc2 = new DataColumn("itemName", Type.GetType("System.String"));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
System.IO.StringReader reader = new System.IO.StringReader(tbxml);
dt.ReadXml(reader);