using System.Xml; XmlWriter writer = XmlWriter.Create("output.xml"); writer.WriteStartElement("books"); writer.WriteStartElement("book"); writer.WriteAttributeString("author", "J.K. Rowling"); writer.WriteElementString("title", "Harry Potter and the Philosopher's Stone"); writer.WriteEndElement(); writer.WriteEndElement(); writer.Flush(); writer.Close();
using System.Xml; XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.Encoding = Encoding.UTF8; XmlWriter writer = XmlWriter.Create("output.xml", settings); writer.WriteStartDocument(); writer.WriteStartElement("books"); writer.WriteStartElement("book"); writer.WriteAttributeString("author", "J.K. Rowling"); writer.WriteElementString("title", "Harry Potter and the Philosopher's Stone"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); writer.Close();This code adds an XML declaration to the document and specifies the encoding type using the XmlWriterSettings class. The System.Xml.XmlWriter library is part of the .NET framework, specifically the System.Xml namespace. No extra package installation is needed to use this library.