using System.Xml; using System.Runtime.Serialization; // Create an XML stream writer XmlWriter xmlWriter = XmlWriter.Create("users.xml"); // Create a new XmlWriterDelegator XmlWriterDelegator writer = new XmlWriterDelegator(xmlWriter); // Start the root element writer.WriteStartElement("Users"); // Write child elements with attributes writer.WriteStartElement("User"); writer.WriteAttributeString("ID", "1"); writer.WriteAttributeString("Name", "John Doe"); writer.WriteEndElement(); writer.WriteStartElement("User"); writer.WriteAttributeString("ID", "2"); writer.WriteAttributeString("Name", "Jane Doe"); writer.WriteEndElement(); // Close the root element writer.WriteEndElement(); // Close the writer writer.Close();
using System.Xml; using System.Runtime.Serialization; [DataContract] public class User { [DataMember] public int ID { get; set; } [DataMember] public string Name { get; set; } } // Create a User object User user = new User { ID = 1, Name = "John Doe" }; // Create an XML stream writer XmlWriter xmlWriter = XmlWriter.Create("user.xml"); // Create a new XmlWriterDelegator XmlWriterDelegator writer = new XmlWriterDelegator(xmlWriter); // Create a new XmlSerializer for User objects DataContractSerializer serializer = new DataContractSerializer(typeof(User)); // Serialize the User object to XML serializer.WriteObject(writer, user); // Close the writer writer.Close();In summary, the System.Runtime.Serialization.XmlWriterDelegator class is a useful tool for writing XML elements and attributes to an output stream. It can be used for creating custom XML files or serializing objects to XML.