using System; using System.Xml; public class WriteXml { public static void Main() { XmlWriter xmlWriter = XmlWriter.Create("example.xml"); xmlWriter.WriteStartElement("myElement"); xmlWriter.WriteString("Hello, World!"); xmlWriter.WriteEndElement(); xmlWriter.Close(); // Closing the XmlWriter to save data to file } }
using (XmlWriter xmlWriter = XmlWriter.Create("example.xml")) { xmlWriter.WriteStartElement("book"); xmlWriter.WriteElementString("title", "The Adventures of Tom Sawyer"); xmlWriter.WriteElementString("author", "Mark Twain"); xmlWriter.WriteEndElement(); } // Automatically closing the XmlWriter using using statementIn this example, using statement is used to automatically close the XmlWriter after writing data. The WriteElementString method is used to add elements and text to the XML file. Finally, the WriteEndElement method is called to close the book element. These examples are using the System.Xml package library.