XmlTextWriter Class
The XmlTextWriter
class provides a fast, non-cached, forward-only way of generating streams or files containing XML data. It implements the XmlWriter
abstract base class.
Overview
Syntax
Members
Example
Key Features
- Supports UTF-8, UTF-16, UTF-32 encoding.
- Provides methods for writing elements, attributes, text, comments, and processing instructions.
- Automatic handling of XML escaping and formatting.
public class XmlTextWriter : XmlWriter, IDisposable
{
public XmlTextWriter(string outputFile);
public XmlTextWriter(Stream output);
public XmlTextWriter(TextWriter writer);
public Formatting Formatting { get; set; }
public XmlNamespaceHandling NamespaceHandling { get; set; }
public bool Indent { get; set; }
public string IndentChars { get; set; }
public bool NewLineOnAttributes { get; set; }
// ... other members
}
Properties
Name | Type | Description |
---|---|---|
Formatting | Formatting | Gets or sets how the output is formatted. |
Indent | bool | Gets or sets whether output is indented. |
IndentChars | string | Gets or sets characters used when indenting. |
NewLineOnAttributes | bool | Gets or sets whether attributes are placed on new lines. |
Methods
Signature | Description |
---|---|
WriteStartDocument() | Writes the XML declaration. |
WriteStartElement(string prefix, string localName, string ns) | Writes a start tag. |
WriteString(string text) | Writes text content. |
WriteEndElement() | Closes the current element. |
WriteComment(string text) | Writes an XML comment. |
Flush() | Flushes whatever is in the buffer to the underlying stream. |
Sample Code
using System;
using System.Xml;
class Program
{
static void Main()
{
using (XmlTextWriter writer = new XmlTextWriter("books.xml"))
{
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
writer.WriteStartDocument();
writer.WriteStartElement("catalog");
writer.WriteStartElement("book");
writer.WriteAttributeString("id", "bk101");
writer.WriteElementString("author", "Gambardella, Matthew");
writer.WriteElementString("title", "XML Developer's Guide");
writer.WriteElementString("genre", "Computer");
writer.WriteElementString("price", "44.95");
writer.WriteElementString("publish_date", "2000-10-01");
writer.WriteElementString("description", "An in-depth look at creating applications with XML.");
writer.WriteEndElement(); //
writer.WriteEndElement(); //
writer.WriteEndDocument();
}
Console.WriteLine("XML file 'books.xml' created successfully.");
}
}