FOR XML and ADO.NET

My esteemed colleague Sahil Malik has blogged about using FOR XML in SQL server.  The following C# example demonstrates how to retrieve XML data from a SQL Server 2K5 database as XML:

using (SqlConnection conn = new SqlConnection(“…”))
{
using (SqlCommand cmd = new SqlCommand(
“select’Rob’ as [Employee/@EmployeeName],’A cool dude’ as [Employee] FOR XML PATH(‘Staff’)”, conn))
{
conn.Open();
XmlReader reader = cmd.ExecuteXmlReader();
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (reader.HasAttributes)
{
Console.Write(“”);
}
else
Console.Write(“”, reader.Name);
break;
case XmlNodeType.Text:
Console.Write(reader.Value);
break;
}
}
}
}

One thought on “FOR XML and ADO.NET

Comments are closed.