I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string. I would hope that there\'s a pub
Unfortunately no, it's not as easy as a FormatXMLForOutput method, this is Microsoft were talking about here ;)
Anyway, as of .NET 2.0, the recommended approach is to use the XMlWriterSettingsClass to set up formatting, as opposed to setting properties directly on the XmlTextWriter object. See this MSDN page for more details. It says:
"In the .NET Framework version 2.0 release, the recommended practice is to create XmlWriter instances using the XmlWriter.Create method and the XmlWriterSettings class. This allows you to take full advantage of all the new features introduced in this release. For more information, see Creating XML Writers. "
Here is an example of the recommended approach:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = (" ");
using (XmlWriter writer = XmlWriter.Create("books.xml", settings))
{
// Write XML data.
writer.WriteStartElement("book");
writer.WriteElementString("price", "19.95");
writer.WriteEndElement();
writer.Flush();
}