Obtain an XML Document from a SQL Server Query : XML Database : Database C# Source Code


Custom Search

C# Source Code » Database » XML Database »

 

Obtain an XML Document from a SQL Server Query








    
 
using System;
using System.Xml;
using System.Data;
using System.Data.SqlClient;

public class XmlQueryExample {

    public static void Main() {
        using (SqlConnection con = new SqlConnection()) {
            con.ConnectionString = "Data Source = localhost;" + 
                "Database = Northwind; Integrated Security=SSPI";
            SqlCommand com = con.CreateCommand();
            com.CommandType = CommandType.Text;
            com.CommandText = "SELECT CustomerID, CompanyName" + 
                " FROM Customers FOR XML AUTO";
            XmlReader reader = null;
            try {
                con.Open();
                reader = com.ExecuteXmlReader();
                while (reader.Read()) {
                    Console.Write(reader.Name);
                    if (reader.HasAttributes) {
                        for (int i = 0; i < reader.AttributeCount; i++) {
                            reader.MoveToAttribute(i);
                            Console.Write("  {0}: {1}",reader.Name, reader.Value);
                        }
                        reader.MoveToElement();  
                    }
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
            } finally {
                if (reader != null) reader.Close();
            }
        }
    }
}

 
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Database
» XML Database