Groups | Blog | Home
all groups > dotnet xml > october 2005 >

dotnet xml : Serializing objects that reference other objects


cjmumford NO[at]SPAM gmail.com
10/29/2005 3:42:37 PM
I have a couple of C# objects like this:

class Foo {

}

class Bar {

Foo m_foo;
Foo foo {
get {
return m_foo;
}
set {
m_foo = value;
}
}
}

What I get when these are serialized is a Foo element nested in a Bar
element. Instead I want it to somehow reference it. Is this possible?
Derek Harmon
10/31/2005 7:08:48 PM
[quoted text, click to view]

You can mark these objects [Serializable] and pump them through a
SOAP Formatter. SOAP encoding allows for "multi-reference
accessors" which is just a fancy way of saying references from
one or more objects to a common [shared] object. MRA is
useful to preserve the identity of the common object (i.e., if each
referring object contained a verbatim nested copy of the common
object, you couldn't say for certain that the common object
was truly the identical object reference across all referrers or
simply an instance that was value-equivalent).

Here is an example,

- - - MultiRefFoo.cs
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

[Serializable]
public class Foo {
private string property;
public Foo( ) {
this.property = "";
}
public string PropertyName {
get {
return this.property;
}
set {
this.property = value;
}
}
public override string ToString( ) {
return string.Format( "Foo[ Property[ {0} ] ]",
this.property);
}
}

[Serializable]
public class Bar {
public Bar( ) {
this.m_foo = new Foo( );
}
private Foo m_foo;
public Foo Foo {
get {
return this.m_foo;
}
set {
this.m_foo = value;
}
}
public override string ToString( ) {
return string.Format( "Bar [ {0} ]",
this.m_foo.ToString( ));
}
}

public class TestApp {
public static void Main( ) {
Bar bar = new Bar( );
bar.Foo = new Foo( );
bar.Foo.PropertyName = "C.J.";

SoapFormatter sf = new SoapFormatter( );
sf.Serialize( Console.OpenStandardOutput( ), bar);
}
}
- - -

Observe that in the resulting XML output, that there are two children of
the SOAP body: Bar and Foo. Notice that the Bar element contains a
reference to the Foo element (by the Foo element's 'id'). If you had
serialized multiple Bar objects, which all referred to the same instance
of Foo, the Foo element you see here would only be serialized once.


Derek Harmon

AddThis Social Bookmark Button