XmlTextWriter writer = new XmlTextWriter("example.xml", System.Text.Encoding.UTF8); writer.WriteStartElement("Root"); // start writing the root element writer.WriteElementString("Element1", "Value1"); // write some data writer.WriteElementString("Element2", "Value2"); writer.WriteEndElement(); // end writing the root element writer.WriteEndDocument(); // end writing the document writer.Close(); // close the writer
using System.IO; using System.Xml; public static void Main() { // Create a new MemoryStream object MemoryStream memoryStream = new MemoryStream(); // Create a new XmlTextWriter object XmlTextWriter writer = new XmlTextWriter(memoryStream, null); // Use the writer object to create an XML document writer.WriteStartDocument(); writer.WriteStartElement("Document"); writer.WriteString("This is some text."); writer.WriteEndElement(); writer.WriteEndDocument(); // Retrieve the XML data from the MemoryStream byte[] data = memoryStream.ToArray(); // Display the XML data as a string string xml = System.Text.Encoding.UTF8.GetString(data); Console.WriteLine(xml); }In this example, the XmlTextWriter is used to write an XML document to a MemoryStream object. The WriteEndDocument method is used to finish writing the document. Finally, the MemoryStream is converted to an array of bytes and displayed as a string to show the XML data that was generated. Package library: System.Xml.