SqlCommand.ExecuteXmlReader : ResultSet to Xml « ADO.Net « C# / CSharp Tutorial





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

class MainClass {
    public static void ConnectedExample() {
        using (SqlConnection con = new SqlConnection()) {
            con.ConnectionString = @"Data Source = .\sqlexpress;Database = Northwind; Integrated Security=SSPI";
            using (SqlCommand com = con.CreateCommand()) {
                com.CommandType = CommandType.Text;
                com.CommandText = "SELECT CustomerID, CompanyName FROM Customers FOR XML AUTO";
                con.Open();
                using (XmlReader reader = com.ExecuteXmlReader()) {
                    while (reader.Read()) {
                        Console.Write("Element: " + 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();
                        }
                    }
                }
            }
        }
    }


    public static void Main(string[] args) {
        ConnectedExample();
    }
}










32.51.ResultSet to Xml
32.51.1.SqlCommand.ExecuteXmlReader
32.51.2.Convert the result from a query to XML and output
32.51.3.Convert the result from a query to XML and output (Disconnected mode)
32.51.4.Save data stored in table to xml file