Serializing an object to an XML file
The following illustrates how to serialize a data structure to an XML file. (Save to an XML file.)
// get the file name. string exportFile = "c:\somefile.xml"; // declare a settings object and set the values. System.Xml.XmlWriterSettings xmlSettings = new System.Xml.XmlWriterSettings(); // set the encoding xmlSettings.Encoding = Encoding.UTF8; // set the indenting to make the results look pretty (optional) xmlSettings.Indent = true; // create an XML Writer object. using (System.Xml.XmlWriter xwr = System.Xml.XmlWriter.Create(exportFile, xmlSettings)) { // create an instance of the XML Serializer object. System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(ourObject.GetType()); // add this to remove the 'xmlns:xsi' & 'xmlns:xsd' attributes from the root node. XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); // serialize the data to our file. x.Serialize(xwr,ourObject);ourObject, ns); // close the XML Writer object. xwr.Close(); }