Sunday, December 28, 2008

XML indentation not working

I'm using an XML file to store a configuration file for the Metalogix Batch Migration Utility. during a recent bug bash, I noticed that the config files were not being properly indented despite the fact that I was setting System.Xml.Formatting.Indented in my code.

// Create an XML writerSystem.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(1000);
System.IO.StringWriter stringWriter = new StringWriter(stringBuilder);
System.Xml.XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.Formatting = System.Xml.Formatting.Indented;
xmlWriter.Indentation = 5; //optionally adjust the indentation
// Write out configuration settings
xmlWriter.WriteStartElement("Configuration");
xmlWriter.WriteRaw("" + txtDBFile.Text + "");

it turned out that the issue was simply that I was using xmlWriter.WriteRaw instead of xmlWriter.WriteElementString. the latter will respect System.Xml.Formatting.Indented and is cleaner code anyway.

to crush this bug, all I had to do was replace the last line (and other similar lines) with this:
xmlWriter.WriteElementString("DBFile", txtDBFile.Text);

No comments: