<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns:MadCap="http://www.madcapsoftware.com/Schemas/MadCap.xsd" MadCap:lastBlockDepth="2" MadCap:lastHeight="120" MadCap:lastWidth="624" MadCap:disableMasterStylesheet="true" MadCap:tocPath="Platform Specific Issues" MadCap:InPreviewMode="false" MadCap:RuntimeFileType="Topic" MadCap:TargetType="WebHelp" MadCap:PathToHelpSystem="../../" MadCap:HelpSystemFileName="index.xml" MadCap:SearchType="Stem"> <head><title>Xml Import-Export In .NET </title> <script type="text/javascript">/* <![CDATA[ */ window.onload = function(){ var pathToFlash = $('html').attr('MadCap:PathToHelpSystem') + 'Content/Resources/Code/ZeroClipboard.swf'; ZeroClipboard.setMoviePath(pathToFlash); function bindToClipBord(element,content){ var clip = new ZeroClipboard.Client(); clip.setText(content); clip.glue(element); }; if(location.protocol==='file:'){ $('.copylink-marker').remove(); } else{ $('.copylink-marker').each(function(){ var text = $(this).parent().parent().children('.prettyprint').html(); $(this).hover(function(){ bindToClipBord(this,text); }, function(){}); }); } prettyPrint(); }; /* ]]> */</script> <link href="../SkinSupport/MadCap.css" rel="stylesheet" /> <link href="../Resources/Stylesheets/OnlineStyle.css" rel="stylesheet" /> <script src="../Resources/Code/prettify.js"> </script> <script src="../Resources/Code/lang-vb.js"> </script> <script src="../Resources/Code/jquery.min.js"> </script> <script src="../Resources/Code/ZeroClipboard.js"> </script> <script src="../SkinSupport/MadCapAll.js" type="text/javascript"> </script> </head> <body> <p class="MCWebHelpFramesetLink" style="display: none;"><a href="../../index_CSH.html#platform_specific_issues/xml_import-export_in_.net.htm" style="">Open topic with navigation</a> </p> <div class="MCBreadcrumbsBox"><span class="MCBreadcrumbsPrefix">You are here: </span><a class="MCBreadcrumbsLink" href="../platform_specific_issues.htm">Platform Specific Issues</a><span class="MCBreadcrumbsDivider"> > </span><span class="MCBreadcrumbs">XML Import-Export In .NET</span> </div> <p> <script type="text/javascript">/*<![CDATA[*/document.write('<a href="' + location.href +'">'); document.write("Direct Link"); document.write('</a>');/*]]>*/</script> </p> <p> </p> <h1>Xml Import-Export In .NET</h1> <p>One of the most widely used platform independent formats of data exchange today is xml.</p> <p>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. </p> <p>All that you need to export your database/query results is:</p> <ol> <li value="1">Retrieve objects from the database.</li> <li value="2">Serialize them in XML format (using language, or external tools, or your own serializing software).</li> <li value="3">Save XML stream (to a disc location, into memory, into another database).</li> </ol> <p>Import process is just the reverse:</p> <ol> <li value="1">Read XML stream</li> <li value="2">Create an objects from XML</li> <li value="3">Save objects to db4o</li> </ol> <p>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).</p> <p>First, let's prepare a database:</p> <p MadCap:conditions="Primary..NET,Primary.c#,Primary.All languages"> <pre class="prettyprint" xml:space="preserve">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(); } }</pre> </p> <p MadCap:conditions="Global.Primary:cs" /> <p MadCap:conditions="Primary..NET,Primary.VB.NET,Primary.All languages"> <pre class="prettyprint lang-vb" xml:space="preserve">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</pre> </p> <p MadCap:conditions="Global.Primary:vb" /> <p>We will save the database to XML file "formula1.xml":</p> <p MadCap:conditions="Primary..NET,Primary.c#,Primary.All languages"> <pre class="prettyprint" xml:space="preserve">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(); } }</pre> </p> <p MadCap:conditions="Global.Primary:cs" /> <p MadCap:conditions="Primary..NET,Primary.VB.NET,Primary.All languages"> <pre class="prettyprint lang-vb" xml:space="preserve">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</pre> </p> <p MadCap:conditions="Global.Primary:vb" /> <p>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.</p> <p>Now we can clean the database and try to recreate it from the XML file:</p> <p MadCap:conditions="Primary..NET,Primary.c#,Primary.All languages"> <pre class="prettyprint" xml:space="preserve">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(); } }</pre> </p> <p MadCap:conditions="Global.Primary:cs" /> <p MadCap:conditions="Primary..NET,Primary.VB.NET,Primary.All languages"> <pre class="prettyprint lang-vb" xml:space="preserve">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</pre> </p> <p MadCap:conditions="Global.Primary:vb" /> <p>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.</p> <p MadCap:conditions="Primary.Online">Download example code:</p> <p MadCap:conditions="Primary.Online"> <MadCap:conditionalText MadCap:conditions="Primary..NET,Primary.VB.NET,Primary.All languages"><a href="serializingvb.zip">VB.NET </a> </MadCap:conditionalText> <MadCap:conditionalText MadCap:conditions="Primary..NET,Primary.c#,Primary.All languages"><a href="serializingcs.zip">c# </a> </MadCap:conditionalText> </p> <script type="text/javascript" src="../SkinSupport/MadCapBodyEnd.js"> </script> </body> </html>