You are here: Platform Specific Issues > XML Import-Export In .NET

Xml Import-Export In .NET

One of the most widely used platform independent formats of data exchange today is xml.

Db4o does not provide any specific API to be used for XML import/export, but with the variety of XML serialization tools available for Java and .NET (freeware and licensed) this is not really necessary.

All that you need to export your database/query results is:

  1. Retrieve objects from the database.
  2. Serialize them in XML format (using language, or external tools, or your own serializing software).
  3. Save XML stream (to a disc location, into memory, into another database).

Import process is just the reverse:

  1. Read XML stream
  2. Create an objects from XML
  3. Save objects to db4o

Let's go through a simple example. We will use .NET XmlSerializer. (You can use any other XML serialization tool, which is able to serialize/deserialize classes).

First, let's prepare a database:

SerializeExample.cs: SetObjects
private static void SetObjects()
     {
      File.Delete(Db4oFileName);
      IObjectContainer db = Db4oFactory.OpenFile(Db4oFileName);
      try 
       {
        Car car = new Car("BMW", new Pilot("Rubens Barrichello"));
        db.Store(car);
        car = new Car("Ferrari", new Pilot("Michael Schumacher"));
        db.Store(car);
      } 
      finally 
       {
        db.Close();
      }
    }

SerializeExample.vb: SetObjects
Private Shared Sub SetObjects()
            File.Delete(Db4oFileName)
            Dim db As IObjectContainer = Db4oFactory.OpenFile(Db4oFileName)
            Try
                Dim car As Car = New Car("BMW", New Pilot("Rubens Barrichello"))
                db.Store(car)
                car = New Car("Ferrari", New Pilot("Michael Schumacher"))
                db.Store(car)
            Finally
                db.Close()
            End Try
        End Sub

We will save the database to XML file "formula1.xml":

SerializeExample.cs: ExportToXml
private static void ExportToXml()
     {
      XmlSerializer carSerializer = new XmlSerializer(typeof(Car[]));
      StreamWriter xmlWriter = new StreamWriter(XmlFileName);
      IObjectContainer db = Db4oFactory.OpenFile(Db4oFileName);
      try 
       {
        IObjectSet result = db.QueryByExample(typeof(Car));
        Car[] cars = new Car[result.Size()];
        for (int i = 0; i < result.Size(); i++)
         {
          Car car = (Car)result[i];
          cars.SetValue(car,i);
        }
        carSerializer.Serialize(xmlWriter, cars);
        xmlWriter.Close();
      }
      finally
       {
        db.Close();
      }
    }

SerializeExample.vb: ExportToXml
Private Shared Sub ExportToXml()
            Dim carSerializer As XmlSerializer = _ 
New XmlSerializer(GetType(Car()))
            Dim xmlWriter As StreamWriter = New StreamWriter(XmlFileName)
            Dim db As IObjectContainer = Db4oFactory. _ 
OpenFile(Db4oFileName)
            Try
                Dim result As IObjectSet = db.QueryByExample(GetType(Car))
                Dim cars() As Car = New Car(result.Size()) {}
                Dim i As Integer
                For i = 0 To result.Size() - 1 Step i + 1
                    Dim car As Car = CType(result(i), Car)
                    cars.SetValue(car, i)
                Next
                carSerializer.Serialize(xmlWriter, cars)
                xmlWriter.Close()
            Finally
                db.Close()
            End Try
        End Sub

After the method executes all car objects from the database will be stored in the export file as an array. Note that child objects (Pilot) are stored as well without any additional settings. You can check the created XML file to see how it looks like.

Now we can clean the database and try to recreate it from the XML file:

SerializeExample.cs: ImportFromXml
private static void ImportFromXml()
     {
      File.Delete(Db4oFileName);
      XmlSerializer carSerializer = new XmlSerializer(typeof(Car[]));
      FileStream xmlFileStream = new FileStream(XmlFileName, FileMode.Open);
      Car[] cars = (Car[])carSerializer.Deserialize(xmlFileStream);
      IObjectContainer db;
      foreach (Car car in cars)
       {
        db = Db4oFactory.OpenFile(Db4oFileName);
        try 
         {
          Car newCar = (Car)car;
          db.Store(newCar);
        } 
        finally 
         {
          db.Close();
        }
      }
      db = Db4oFactory.OpenFile(Db4oFileName);
      try 
       {
        IObjectSet result = db.QueryByExample(typeof(Pilot));
        ListResult(result);
        result = db.QueryByExample(typeof(Car));
        ListResult(result);
      } 
      finally 
       {
        db.Close();
      }
    }

SerializeExample.vb: ImportFromXml
Private Shared Sub ImportFromXml()
            File.Delete(Db4oFileName)
            Dim carSerializer As XmlSerializer = New _ 
XmlSerializer(GetType(Car()))
            Dim xmlFileStream As FileStream = New _ 
FileStream(XmlFileName, FileMode.Open)
            Dim cars() As Car = CType(carSerializer. _ 
Deserialize(xmlFileStream), Car())
            Dim db As IObjectContainer
            Dim car As Car
            For Each car In cars
                db = Db4oFactory.OpenFile(Db4oFileName)
                Try
                    Dim newCar As Car = CType(car, Car)
                    db.Store(newCar)
                Finally
                    db.Close()
                End Try
            Next
            db = Db4oFactory.OpenFile(Db4oFileName)
            Try
                Dim result As IObjectSet = db.QueryByExample(GetType(Pilot))
                ListResult(result)
                result = db.QueryByExample(GetType(Car))
                ListResult(result)
            Finally
                db.Close()
            End Try
        End Sub

Easy, isn't it? Obviously there is much more about XML serialization: renaming fields, storing collections, selective persistence etc. You should be able to find detailed description together with the serialization library, which you will use.

Download example code:

VB.NET c#