Reputation: 19377
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>
Upvotes: 0
Views: 1303
Reputation: 19377
One approach is to use an XMLDocument and an XMLTextWriter.
using (XmlReader reader = xmlCommand.ExecuteXmlReader())
{
XmlDocument dom = new XmlDocument();
dom.Load(reader);
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
using (var writer = XmlTextWriter.Create("file2.xml", settings))
{
dom.WriteContentTo(writer);
}
}
It gets the job done but it seems like a lot of code to accomplish a simple task.
Upvotes: 1