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

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 libraries available.

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

  1. Retrieve objects from the database.
  2. Serialize them in XML format using your favorite serialization API/library
  3. Save XML stream (to a disc location, into memory, into another database).

Import process is just the reverse:

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

Let's go through a simple example. We will use XStream library (http://xstream.codehaus.org/) for object serialization, but any other tool capable of serializing objects into XML will do as well.

ObjectContainer container = Db4oEmbedded.openFile("database.db4o");
try {
    Pilot[] pilots = container.query(Pilot.class).toArray(new Pilot[0]);
    XStream xstream = new XStream();
    OutputStream stream = new FileOutputStream("pilots.xml");
    try {
        xstream.toXML(pilots, stream);
    } finally {
        stream.close();
    }
} finally {
    container.close();
}
XMLSerialisationExamples.java: Serialize to XML

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:

ObjectContainer container = Db4oEmbedded.openFile("database.db4o");
try {
    XStream xstream = new XStream();
    InputStream stream = new FileInputStream("pilots.xml");
    try {
        Pilot[] pilots = (Pilot[]) xstream.fromXML(stream);
        for (Pilot pilot : pilots) {
            container.store(pilot);
        }
    } finally {
        stream.close();
    }
} finally {
    container.close();
}
XMLSerialisationExamples.java: Read objects from XML

Obviously there is much more to 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.