Posting both question and (one) answer here to see if somebody has a better solution…
I am trying to write formatted XML output from stored procedure to file. My first attempt looked like this:
// the actual command is a stored procedure that returns an XML document, but use this for demo purposes
var xmlCommand = new SqlCommand("SELECT 1 as ID, 'asdf' as Name FOR XML PATH, ROOT('MyData')", conn);
File.WriteAllText("file1.xml", (string)xmlCommand.ExecuteScalar());
Which was nice and short, but the file generated has everything stuffed on one line:
<MyData><row><ID>1</ID><Name>asdf</Name></row></MyData>
I want it to be formatted nicely:
<MyData>
<row>
<ID>1</ID>
<Name>asdf</Name>
</row>
</MyData>
One approach is to use an XMLDocument and an XMLTextWriter.
It gets the job done but it seems like a lot of code to accomplish a simple task.