XmlTextWriter.Formatting Property

Definition

Indicates how the output is formatted.

public System.Xml.Formatting Formatting { get; set; }

Property Value

One of the Formatting values. The default is Formatting.None (no special formatting).

Examples

The following example writes an XML fragment.

using System;
using System.IO;
using System.Xml;

public class Sample
{

  public static void Main()
  {
     //Create a writer to write XML to the console.
     XmlTextWriter writer = null;
     writer = new XmlTextWriter (Console.Out);

     //Use indentation for readability.
     writer.Formatting = Formatting.Indented;
     writer.Indentation = 4;

     //Write an element (this one is the root).
     writer.WriteStartElement("book");

     //Write the title element.
     writer.WriteStartElement("title");
     writer.WriteString("Pride And Prejudice");
     writer.WriteEndElement();

     //Write the close tag for the root element.
     writer.WriteEndElement();

     //Write the XML to file and close the writer.
     writer.Close();
  }
}

Remarks

Note

Starting with the .NET Framework 2.0, we recommend that you create XmlWriter instances by using the XmlWriter.Create method and the XmlWriterSettings class to take advantage of new functionality.

If the Indented option is set, child elements are indented using the Indentation and IndentChar properties. Only element content is indented. The following C# code writes out HTML elements including mixed content:

XmlTextWriter w = new XmlTextWriter(Console.Out);
 w.Formatting = Formatting.Indented;
 w.WriteStartElement("ol");
 w.WriteStartElement("li");
 w.WriteString("The big "); // This means "li" now has a mixed content model.
 w.WriteElementString("b", "E");
 w.WriteElementString("i", "lephant");
 w.WriteString(" walks slowly.");
 w.WriteEndElement();
 w.WriteEndElement();

The above code produces the following output:

<ol>
  <li>The big <b>E</b><i>lephant</i> walks slowly.</li>
</ol>

When this is viewed in HTML no white space appears between the bold and italic elements. In fact, in this example, if indenting was added between these elements the word "Elephant" would be incorrectly broken.

Note

Writing any text content, excluding String.Empty puts that element into mixed content mode. Child elements do not inherit this "mixed" mode status. A child element of a "mixed" element does indenting, unless it is also contains "mixed" content. Element content and mixed content are defined according to the XML 1.0 definitions of these terms.

Applies to

Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

See also