Mega Code Archive

 
Categories / C# Tutorial / ADO Net
 

Convert the result from a query to XML and output (Disconnected mode)

using System; using System.Xml; using System.Data; using System.Data.SqlClient; class MainClass {     public static void Main(string[] args)     {         XmlDocument doc = new XmlDocument();         using (SqlConnection con = new SqlConnection())         {             con.ConnectionString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;";             SqlCommand com = con.CreateCommand();             com.CommandType = CommandType.Text;             com.CommandText = "SELECT ID, FirstName FROM Employee FOR XML AUTO";             con.Open();             XmlReader reader = com.ExecuteXmlReader();             doc.LoadXml("<results></results>");             XmlNode newNode = doc.ReadNode(reader);             while (newNode != null)             {                 doc.DocumentElement.AppendChild(newNode);                 newNode = doc.ReadNode(reader);             }         }         Console.WriteLine(doc.OuterXml);     } }