kasajian
5/19/2014 - 8:23 PM

Store C# class for streaming / serializing .NET objecfts to XML

Store C# class for streaming / serializing .NET objecfts to XML

See Mee

(http://www.google.com)

This class stores and loads .xml files into C# objects. File: Store.cs:

Store.cs

Can be used with no new types. File: notypes_example.cs:

notypes_example.cs

Produces output such as. File: notypes_example.xml

notypes_example.xml

top

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ArrayOfString>
    <string>k1</string>
    <string>v1</string>
  </ArrayOfString>
  <ArrayOfString>
    <string>k2</string>
    <string>v2</string>
  </ArrayOfString>
</ArrayOfArrayOfString>
string[][] x = 
{
    new [] { "k1", "v1" },
    new [] { "k2", "v2" },
};

Store<string[][]>.Save(@"myobject.xml", x);
using System.IO;
using System.Xml.Serialization;

//--------------------------------------------------------------------------
// Saves an object to an XML file and Loads an object from an XML file.
//
// Examples -- saves to a file:
//      CMyClass myobject;
//      myobject = ....
//      Store<CMyClass>.Save("myobject.xml", myobject);
//
// Examples -- loads from file:
//      CMyClass myobject = Store<CMyClass>.Load("myobject.xml);
//--------------------------------------------------------------------------

public class Store<T>
{
    // For use with FileStream, MemoryStream, etc.
    public static void Save(Stream stream, T theObject)
    {
        new XmlSerializer(typeof(T)).Serialize(stream, theObject);
    }

    // Store the object to the specified file
    public static void Save(string filename, T theObject)
    {
        using (TextWriter stream = new StreamWriter(filename))
            new XmlSerializer(typeof(T)).Serialize(stream, theObject);
    }

    // For use with FileStream, MemoryStream, etc.
    public static T Load(Stream stream)
    {
        return (T)(new XmlSerializer(typeof(T)).Deserialize(stream));
    }

    // Store the object to the specified file
    public static T Load(string filename)
    {
        using (TextReader stream = new StreamReader(filename))
            return (T)(new XmlSerializer(typeof(T)).Deserialize(stream));
    }
     
}