Data export to XML file
#region data is exported to XML file string sql = "Select Id, Callernumber, Telnum, StartDateTime, EndDateTime from Chens. Callrecords "; XDocument XDoc = new XDocument (); Create root directory 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 ("Data export complete"); Console.readkey (); #endregion
2. Importing data from an XML file into a database
#region Import the data from the XML file into the database string sql; XDocument XDoc = xdocument.load ("person.xml"); using (SqlConnection conn=new SqlConnection (sconstr)) {using (SqlCommand cmd=new SqlCommand ()) {cmd. Connection = conn; Conn. Open (); Iterate through each of the caller node 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; Updates the resulting value back to database cmd. ExecuteNonQuery (); }}} Console.WriteLine ("Data import Complete"); Console.readkey (); #endregion
Ado. NET notes (i) XML import Export and database