Obtain an XML Document from a SQL Server Query : XML Database « Database ADO.net « C# / C Sharp






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();
            }
        }
    }
}

 








Related examples in the same category

1.Fill data in DateSet to XmlDocument
2.causes the the child rows to be nested within the parent rows in the output XML
3.illustrates how to write and read XML files
4.Persisting A Dataset To An XML File
5.Reading An XML File Into A Dataset