If you only need to save the XML and not do anything else, this is probably the easiest way to do this - using a simple simple ADO.NET:
string query = "SELECT EmployeeID, LastName, FirstName, Title, BirthDate, HireDate FROM dbo.Employees FOR XML AUTO"; using(SqlConnection _con = new SqlConnection("server=(local);database=Northwind;integrated security=SSPI;")) using (SqlCommand _cmd = new SqlCommand(query, _con)) { _con.Open(); string result = _cmd.ExecuteScalar().ToString(); _con.Close(); File.WriteAllText(@"D:\test.xml", result); }
This will create the file D:\test.xml (or modify it according to your system) and place these XML tags in this file.
The SqlCommand object also has a .ExecuteXmlReader() method, which returns an XmlReader object for scanning and manipulating XML - it does not just return a string. Use what suits you best!
PS: also the output of FOR XML AUTO bit ... let ... suboptimal. It uses dbo.Employee as the main XML tag, etc ... with SQL Server 2008, I would strongly recommend that you use FOR XML PATH instead - it allows you to customize and customize the XML output layout.
Compare XML source output with FOR XML AUTO
<dbo.Employees _x0040_ID="1" LastName="Davolio" FirstName="Nancy" Title="Sales Representative" BirthDate="1948-12-08T00:00:00" HireDate="1992-05-01T00:00:00" /> <dbo.Employees _x0040_ID="2" LastName="Fuller" FirstName="Andrew" Title="Vice President, Sales" BirthDate="1952-02-19T00:00:00" HireDate="1992-08-14T00:00:00" />
against this query - just to see the difference:
SELECT [EmployeeID] AS '@ID', [LastName], [FirstName], [Title], [BirthDate], [HireDate] FROM [dbo].[Employees] FOR XML PATH('Employee'), ROOT('Employees')
Exit:
<Employees> <Employee ID="1"> <LastName>Davolio</LastName> <FirstName>Nancy</FirstName> <Title>Sales Representative</Title> <BirthDate>1948-12-08T00:00:00</BirthDate> <HireDate>1992-05-01T00:00:00</HireDate> </Employee> <Employee ID="2"> <LastName>Fuller</LastName> <FirstName>Andrew</FirstName> <Title>Vice President, Sales</Title> <BirthDate>1952-02-19T00:00:00</BirthDate> <HireDate>1992-08-14T00:00:00</HireDate> </Employee>