XmlTextWriter writer = new XmlTextWriter("example.xml", System.Text.Encoding.UTF8); writer.WriteStartDocument(); writer.WriteStartElement("root"); writer.WriteStartElement("child1"); writer.WriteEndElement(); writer.WriteStartElement("child2"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close();
Stream stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8); writer.WriteStartDocument(); writer.WriteStartElement("root"); writer.WriteStartElement("child1"); writer.WriteEndElement(); writer.WriteStartElement("child2"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); stream.Position = 0; StreamReader reader = new StreamReader(stream); string xml = reader.ReadToEnd();In this example, a MemoryStream is used to store the XML data. The XmlTextWriter is created with the stream as the first parameter, so that the XML data will be written to it. The Flush() method is used to ensure that all XML data has been written to the stream. Finally, the stream is reset to the beginning and the XML data is read from the stream and stored in a string variable. The XmlTextWriter class is found in the System.Xml namespace, which is part of the .NET Framework.