XML serialization

  • Thread starter Thread starter Arjen
  • Start date Start date
A

Arjen

Hello,

I'm currently doing this:

ObjectA[] aObjectA = new ObjectA[ObjectA.tabel.Count];
ObjectA.tabel.Values.CopyTo( aObjectA, 0 );

XmlSerializer x = new XmlSerializer( typeof(ObjectA[]) );
TextWriter writer = new StreamWriter( "DATA.xml" );
x.Serialize( writer, aObjectA );

And this is working perfectly!

Now I have also a ObjectB.
I want to serialize this in the same DATA.xml file.

Can somebody give me an example how to do this?

Thanks!
 
As XML documents can only have a single root node, you can only serialize
one object graph into a document. You just need to make a root type that
contains all of your instances. Using your naming conventions:

class Things
{
ObjectA[] _a;
ObjectB[] _b;

public Things(ObjectA[] a, ObjectB[] b)
{
_a = a;
_b = b;
}

public ObjectA[] CollectionOfA
{
get { return _a; }
set { _a = value; }
}
public ObjectB[] CollectionOfB
{
get { return _b; }
set { _b = value; }
}
}

Create your array of ObjectA. Create your array of ObjectB. Create an
instance of Things:

Things things = new Things(aObjectA, aObjectB);
XmlSerializer x = new XmlSerializer( typeof(Things) );
TextWriter writer = new StreamWriter( "DATA.xml" );
x.Serialize( writer, things );
 
Hello,

Thanks for your answer!

I'm trying to get the data back from the XML document.
But how do I get it back there?

I have also changed a little bit my code... under my message you can see my
code.
The comments like "// And whats next?", there should be some code...
Can you help me a bit?

Thanks!
Arjen




namespace ProgramMainName {

class ProgramMainName {

public static Hashtable ObjectsA = new Hashtable();
public static Hashtable ObjectsB = new Hashtable();

/// <summary>
/// The main!
/// </summary>
[STAThread]
static void Main(string[] args) {
// To do something, like: XMLSerialization.Open()
}
}
}





namespace ProgramMainName {
public class XMLSerialization {

public static void Open() {

XmlSerializer x = new XmlSerializer( typeof( ProgramMainName ) );

FileStream fs = null;
try {
fs = new FileStream( "data.xml", FileMode.Open );

XmlReader reader = new XmlTextReader( fs );
ProgramMainName programMainName = (ProgramMainName) x.Deserialize(
reader );
// And whats next?
}
catch( FileNotFoundException ) {

}
finally {
if ( fs != null )
fs.Close();
}
}
}

public static void Save() {
// And whats next?
}
}
 
Back
Top