NMath User's Guide

TOC |  Previous |  Next |  Index

30.3 XML Serialization (.NET, C#, CSharp, Visual Basic, VB.NET)

XML serialization in .NET does not make use of CLR Formatter classes, as do binary serialization (Section 30.1) and SOAP serialization (Section 30.2). Instead, the framework provides the System.Xml.Serialization.XmlSerializer class for persisting to XML documents.

However, because NMath data classes implement the IEnumerable interface, XmlSerializer persists only the enumerated data. Thus, though a matrix or vector object can be serialized in XML, it cannot be restored.

If you want to serialize and deserialize NMath objects in XML format, you can easily overcome this limitation by writing a simple wrapper class that contains all the information necessary to restore the object, without implementing IEnumerable. For example, this code defines an MyNameSpace.MyWrapper class that wraps a DoubleMatrix:

using CenterSpace.NMath.Core;

namespace MyNamespace
{
  public class MyWrapper
  {
    public int Rows;
    public int Columns;
    public StorageType Storage = StorageType.ColumnMajor;
    public double[] Data;

    public MyWrapper() {}

    public MyWrapper( DoubleMatrix A )
    {
      Rows = A.Rows;
      Columns = A.Cols;
      DoubleMatrix B = (DoubleMatrix)A.Clone();
      Data = B.DataBlock.Data;
    }

  }  // class

} // namespace

Note that the constructor uses the Clone() method to ensure that the data is not referenced by any other objects, and that it is in contiguous storage.

You could then use the wrapper class to serialize a matrix object, as shown below:

using System.IO;
using System.Xml.Serialization;
using MyNamespace;

DoubleMatrix A = new DoubleMatrix( "3x3[1 2 3 4 5 6 7 8 9]" );
MyWrapper AWrap = new MyWrapper( A );

XmlSerializer x = new XmlSerializer( typeof( MyWrapper ) );
FileStream s = File.Create( "myData.xml" );
x.Serialize( s, W );
s.Close();

To restore the object:

s = File.OpenRead( "myData.xml" );
MyWrapper AWrap = (MyWrapper)x.Deserialize( s );
DoubleMatrix A = new DoubleMatrix( AWrap.Rows, AWrap.Columns, 
                                   AWrap.Data, AWrap.Storage ); 

TOC |  Previous |  Next |  Index