Mega Code Archive

 
Categories / C# / ADO Database
 

How to write and read XML files

using System; using System.Data; using System.Data.SqlClient; class WriteAndReadXML {     public static void Main() {         SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa");         SqlCommand mySqlCommand = mySqlConnection.CreateCommand();         mySqlCommand.CommandText =           "SELECT TOP 2 CustomerID, CompanyName, ContactName, " +           "Address " +           "FROM Customers " +           "ORDER BY CustomerID";         SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();         mySqlDataAdapter.SelectCommand = mySqlCommand;         DataSet myDataSet = new DataSet();         mySqlConnection.Open();         mySqlDataAdapter.Fill(myDataSet, "Customers");         mySqlConnection.Close();         myDataSet.WriteXml("myXmlFile.xml");         myDataSet.WriteXml("myXmlFile2.xml", XmlWriteMode.WriteSchema);         myDataSet.WriteXmlSchema("myXmlSchemaFile.xml");         myDataSet.Clear();         myDataSet.ReadXml("myXmlFile.xml");         DataTable myDataTable = myDataSet.Tables["Customers"];         foreach (DataRow myDataRow in myDataTable.Rows) {             Console.WriteLine("CustomerID = " + myDataRow["CustomerID"]);             Console.WriteLine("CompanyName = " + myDataRow["CompanyName"]);             Console.WriteLine("ContactName = " + myDataRow["ContactName"]);             Console.WriteLine("Address = " + myDataRow["Address"]);         }     } }