Namespace: System.Xml
Inheritance: Object → MarshalByRefObject → XmlWriter
Provides a fast, forward-only way to send stream of XML documents.
This class is abstract and should be inherited from. Use XmlWriter.Create to create an instance of XmlWriter.
Creates an XmlWriter that sends XML data to the specified stream.
Creates an XmlWriter that sends XML data to the specified stream with the specified settings.
Creates an XmlWriter that sends XML data to the specified text writer.
Creates an XmlWriter that sends XML data to the specified text writer with the specified settings.
Writes the XML declaration, such as <?xml version="1.0" encoding="UTF-8"?>.
Writes the start tag for the specified element.
Writes the end tag for the current element.
Writes the specified string content.
Writes an attribute with the specified value.
Closes this stream and flushes any buffered data.
The XmlWriter class provides a mechanism for writing XML documents. It is designed for performance and efficient writing of XML data. You can control the formatting, indentation, and other aspects of the XML output by using XmlWriterSettings.
Key features include:
using System;
using System.IO;
using System.Xml;
public class Example
{
public static void Main(string[] args)
{
// Create XmlWriterSettings to specify indentation
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " "; // Use 4 spaces for indentation
// Create an XmlWriter to write to a string
using (StringWriter sw = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sw, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("root");
writer.WriteAttributeString("version", "1.0");
writer.WriteStartElement("child");
writer.WriteString("Hello, XML!");
writer.WriteEndElement(); // End child
writer.WriteEndElement(); // End root
writer.WriteEndDocument();
}
Console.WriteLine(sw.ToString());
}
}
}