Skip to content

Instantly share code, notes, and snippets.

@lmatt-bit
Created March 9, 2012 03:30
Show Gist options
  • Select an option

  • Save lmatt-bit/2004868 to your computer and use it in GitHub Desktop.

Select an option

Save lmatt-bit/2004868 to your computer and use it in GitHub Desktop.
SQL to XML
XElement root = new XElement("Orders");
using (SqlConnection con = new SqlConnection("data source=LMATT-PC\\SQLEXPRESS;integrated security=SSPI"))
{
con.Open();
using(SqlCommand command = new SqlCommand("SELECT top 50 * from Spt_values", con))
{
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
root.AddFirst(
new XElement("Order",
from i in Enumerable.Range(0, reader.FieldCount)
select
new XElement(reader.GetName(i), reader.GetValue(i))
)
);
}
root.Save(Console.Out);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment