数据导出成XML文件
#region 数据导出成XML文件 string sql = "select Id, CallerNumber, TelNum, StartDateTime, EndDateTime from chens.CallRecords"; XDocument xDoc = new XDocument(); //创建根目录 XElement person = new XElement("person"); xDoc.Add(person); using (SqlConnection conn = new SqlConnection(sConstr)) { using (SqlCommand cmd = new SqlCommand(sql, conn)) { conn.Open(); using (SqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { XElement caller = new XElement("caller"); for (int i = 0; i < sdr.FieldCount; i++) { caller.SetElementValue(sdr.GetName(i), sdr.GetValue(i).ToString()); } person.Add(caller); } } } } xDoc.Save("person.xml"); Console.WriteLine("数据导出完毕"); Console.ReadKey(); #endregion
2.将XML文件中的数据导入数据库
#region 将XML文件中的数据导入数据库 string sql; XDocument xDoc = XDocument.Load("person.xml"); using (SqlConnection conn=new SqlConnection(sConstr)) { using (SqlCommand cmd=new SqlCommand()) { cmd.Connection = conn; conn.Open(); //遍历每一个caller节点 foreach (XElement item in xDoc.Element("person").Elements("caller")) { int Id = Convert.ToInt32(item.Element("Id").Value); string CallerNumber = item.Element("CallerNumber").Value; string TelNum = item.Element("TelNum").Value; DateTime StartDateTime = Convert.ToDateTime(item.Element("StartDateTime").Value); DateTime EndDateTime = Convert.ToDateTime(item.Element("EndDateTime").Value); sql = string.Format("insert into chens.CallRecords(Id, CallerNumber, TelNum, StartDateTime, EndDateTime)values({0},'{1}','{2}','{3}','{4}')", Id, CallerNumber, TelNum, StartDateTime, EndDateTime); cmd.CommandText = sql; //将得到的值更新回数据库 cmd.ExecuteNonQuery(); } } } Console.WriteLine("数据导入完毕"); Console.ReadKey(); #endregion