Using XmlReader to read Xml result set from database : XmlReader « XML « C# / CSharp Tutorial






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

public class DirectXML
{
    private static string connectionString = "Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI";

    public static void Main() 
    {
        string SQL = "SELECT CategoryID, CategoryName, Description FROM Categories FOR XML AUTO";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand com = new SqlCommand(SQL, con);
        try
        {
            con.Open();
            XmlReader reader = com.ExecuteXmlReader();
            while (reader.Read())
            {
                Console.WriteLine(reader.Name);
                if (reader.HasAttributes)
                {
                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToAttribute(i);
                        Console.Write(reader.Name + ": " + reader.Value);
                    }
                    reader.MoveToElement();
                }
            }
            reader.Close();
        }
        catch (Exception err)
        {
            Console.WriteLine(err.ToString());
        }
        finally
        {
            con.Close();
        }
    }
}








30.5.XmlReader
30.5.1.XmlReader: ReadElementContentAsString
30.5.2.Create XmlReader from Stream
30.5.3.Using XmlReader to read Xml result set from database
30.5.4.XmlReaderSettings and XmlWriterSettings
30.5.5.XmlTextReader in Action
30.5.6.Read Xml output from database
30.5.7.Chaining an XmlReader to an XmlWriter
30.5.8.extends XmlReader to wrap Sql statement
30.5.9.Create the validating reader