Not logged in - Login

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 = new UTF8Encoding(false); // use this line to prevent '?' character at beginning
//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("", "");

    // the above doesn't alway work to remove the xmlns attributes if a default xmlns is supposed to be there, do this instead
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces(
      new new System.Xml.XmlQualifiedName[]
        new System.Xml.XmlQualifiedName("", "")

    // serialize the data to our file.
    x.Serialize(xwr, ourObject, ns);

    // close the XML Writer object.