XmlTextWriter writer = new XmlTextWriter("output.xml", null); // create a new XmlTextWriter object writer.WriteStartElement("students"); // start the root element writer.WriteStartElement("student"); // start an element writer.WriteAttributeString("name", "John"); // write an attribute writer.WriteEndElement(); // end the element writer.Close(); // close the writer and save the file
using System.IO; using System.Xml; ... XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineOnAttributes = true; using (XmlTextWriter writer = new XmlTextWriter("output.xml", null)) { writer.Formatting = Formatting.Indented; writer.WriteStartElement("root"); // write some data writer.WriteEndElement(); writer.Close(); }This code creates an XmlTextWriter object using a using statement, which ensures that the writer is closed even if an exception is thrown. It also sets some XmlWriterSettings to enable indentation and new lines after attributes, writes some data to the output, and closes the writer. The XmlTextWriter class is part of the System.Xml namespace and is included in the .NET Framework.