Indentation and new line command for XMLwriter in C#

I am writing some data to XML file...but when I open it all the values are in a single line...how can write it in readable format?ie each node in new line and indentation?

FileStream fs = new FileStream("myfile.xml", FileMode.Create);

XmlWriter w = XmlWriter.Create(fs);

w.WriteStartDocument();
w.WriteStartElement("myfile");                 

w.WriteElementString("id", id.Text);
w.WriteElementString("date", dateTimePicker1.Text);
w.WriteElementString("version", ver.Text);
w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();

Answers


Use a XmlTextWriter instead of XmlWriter and then set the Indentation properties.

Example

string filename = "MyFile.xml";

using (FileStream fileStream = new FileStream(filename, FileMode.Create))
using (StreamWriter sw = new StreamWriter(fileStream))
using (XmlTextWriter xmlWriter = new XmlTextWriter(sw))
{
  xmlWriter.Formatting = Formatting.Indented;
  xmlWriter.Indentation = 4;

  // ... Write elements
}

Following @jumbo comment, this could also be implemented like in .NET 2.

var filename = "MyFile.xml";
var settings = new XmlWriterSettings() 
{
    Indent = true,
    IndentChars = "    "
}

using (var w = XmlWriter.Create(filename, settings))
{
    // ... Write elements
}

You need to first create an XmlWriterSettings object that specifies your indentation, then when creating your XmlWriter, pass in the XmlWriterSettings after your path.

Additionally, I use the using block to let C# handle the disposing of my resources so that I don't need to worry about losing any resources on an exception.

{
  XmlWriterSettings xmlWriterSettings = new XmlWriterSettings()
  {
    Indent = true,
    IndentChars = "\t",
    NewLineOnAttributes = true
  };

  using (XmlWriter w= XmlWriter.Create("myfile.xml", xmlWriterSettings))
  {
    w.WriteStartDocument();
    w.WriteStartElement("myfile");

    w.WriteElementString("id", id.Text);
    w.WriteElementString("date", dateTimePicker1.Text);
    w.WriteElementString("version", ver.Text);
    w.WriteEndElement();
    w.WriteEndDocument();
  }
}

Check the Settings property:

w.Settings.Indent = true;

Edit: You can't set it directly:

System.Xml.XmlWriter.Create("path", new System.Xml.XmlWriterSettings())

Set the Formatting Property of the XmlTextWriter:

TextWriter textWriter;
var xmlTextWriter = new XmlTextWriter(textWriter);
xmlTextWriter.Formatting = Formatting.Indented;

Use Settings As follow:

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Encoding = Encoding.UTF8;
        settings.Indent = true;

        using (MemoryStream memoryStream = new MemoryStream())
        using (XmlWriter xmlDoc = XmlWriter.Create(memoryStream, settings)){
         // logic here..
        }

This will get you where you want, though, you don't have to use MemoryStream, the importent part is the settings.


A little VB.NET version using XmlWriter plus XmlWriterSettings direct to file:

Dim oSerializer As New XmlSerializer(GetType(MyType), New XmlRootAttribute("MyRootAttributeName"))
Using oXmlWriter As XmlWriter = XmlWriter.Create("MyFilePath", New XmlWriterSettings With {.Indent = True}) //Default encoding is utf-8
    oSerializer.Serialize(oXmlWriter, oInstanceOfMyType)
    oXmlWriter.Flush()
End Using

Check the doco for other settings and file overwrite options but this is clean and works as expected in lots of situations.


Need Your Help

Split text into sentences in C#

c# text split

I want to divide a text into sentences. A sentence ends with (dot) or ? or ! followed by one or more whitespace characters followed and the next sentence starts with an uppercase letter.

line breaks in a textarea

php html textarea line-breaks nl2br

I know when saving a textarea you can use the nl2br() or str_replace to change the /n to br tags etc. However what im not sure about how to insert line breaks into a textarea. I cant seem to find m...