XML to memory file

Here is a sample about XML and memory file:

    /// <summary>
    /// Method to convert a custom Object to XML string
    /// </summary>
    /// <param name=”pObject”>Object that is to be serialized to XML</param>
    /// <returns>XML string</returns>

    public String SerializeObject ( Object pObject )
    {
        try
        {
            String XmlizedString = null;

            MemoryStream memoryStream = new MemoryStream ( );
            XmlSerializer xs = new XmlSerializer ( typeof ( Animal ) );
            XmlTextWriter xmlTextWriter = new XmlTextWriter ( memoryStream, Encoding.UTF8 );

            xs.Serialize ( xmlTextWriter, pObject );
            memoryStream = ( MemoryStream ) xmlTextWriter.BaseStream;
            XmlizedString = UTF8ByteArrayToString ( memoryStream.ToArray ( ) );
            return XmlizedString;
        }
        catch ( Exception e )
        {
            System.Console.WriteLine ( e );
            return null;
        }
    }

    /// <summary>
    /// Method to reconstruct an Object from XML string
    /// </summary>
    /// <param name=”pXmlizedString”></param>
    /// <returns></returns>
    public Object DeserializeObject ( String pXmlizedString )
    {
        XmlSerializer xs = new XmlSerializer ( typeof ( Automobile ) );
        MemoryStream memoryStream = new MemoryStream ( StringToUTF8ByteArray ( pXmlizedString ) );
        XmlTextWriter xmlTextWriter = new XmlTextWriter ( memoryStream, Encoding.UTF8 );
 
        return xs.Deserialize ( memoryStream );
    }

Above code from dotnetjohn, about more details, please read their website.

A nice XMLSerialize sample using C#

The code sample is from the book “C# Design and Development: Expert One on One“:

First, we have a Names class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace XMLSerialize
{
   [Serializable()]
   public class Names
   {
      public String FirstName{get;set;}
      public String LastName{get;set;}

      // The default constructor.
      public Names()
      {
      }

      // A contructor that accepts inputs.
      public Names (String NewFirstName, String NewLastName)
      {
         FirstName = NewFirstName;
         LastName = NewLastName;
      }
   }
}

then we have a Setting class which uses XML Serialize:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace XMLSerialize
{
   public class Settings
   {
      // A list of names stored by the program.
      public Names[] NameList{get;set;}

      // The last date the user used the program.
      public DateTime LastVisit{get;set;}

      public static Settings LoadSettings()
      {
         // Create a user-specific settings string.
         String UserPath =
            Environment.GetFolderPath(
               Environment.SpecialFolder.ApplicationData) +
            @"\XMLSerialize";

         // Determine whether the application settings exist.
         if (!File.Exists(UserPath + @"\AppData.CONFIG"))
            return null;

         // Define an XML serializer.
         XmlSerializer DataRead =
            new XmlSerializer(typeof(Settings));

         // Create a stream writer to read the data.
         StreamReader Input =
            new StreamReader(UserPath + @"\AppData.CONFIG");

         // Load the settings.
         Settings Current;
         Current = (Settings)DataRead.Deserialize(Input);
         Input.Close();

         // Return the current settings.
         return Current;
      }

      public static void SaveSettings(Settings Current)
      {
         // Uncomment the following lines to see LINQ sorting at work!

         //// Sort the Current data so it appears sorted on disk.
         //IEnumerable<Names> Sorted =
         //   Current.NameList.OrderBy(
         //      Names => Names.FirstName + Names.LastName);
         //Current.NameList = Sorted.ToArray<Names>();

         // Create a user-specific settings string.
         String UserPath =
            Environment.GetFolderPath(
               Environment.SpecialFolder.ApplicationData) +
            @"\XMLSerialize";

         // Determine whether the directory exists.
         if (!Directory.Exists(UserPath))
            Directory.CreateDirectory(UserPath);

         // Define an XML serializer.
         XmlSerializer DataWrite =
            new XmlSerializer(typeof(Settings));

         // Create a stream writer to output the data.
         StreamWriter Output =
            new StreamWriter(UserPath + @"\AppData.CONFIG");

         // Save the settings.
         DataWrite.Serialize(Output, Current);

         // Flush and close the output file.
         Output.Flush();
         Output.Close();
      }
   }
}

then we can use the Setting class somewhere . All detail code please read the book I mentioned.