473,563 Members | 2,856 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Xml Serializing subclass problem

Hi guys. I've come across a problem when I tried to serialize a class into
xml, only to discover that the parent class's XML Serialization properties
weren't included in the output xml.

Actually, the class I'm serializing is two steps down in the inheritance
ladder. It's got a parent class which also has a parent class :( All those
classes in the hierarchy are Xml Serializable, and I'd think that it should
be obvious that all attributes/properties of the parents should be
serialized for any given subclass, no ?
Here's the two classes, subclass first, parent classes afterwards:
[XmlRootAttribut e(Namespace="", ElementName="Gr oup", IsNullable=fals e)]
public class Group : CBusLogicalObje ct
{
private Unit[] m_units = null;
public Group() : base()
{
}
public Group(string strAddress, CBusNode parent)
: base(strAddress , parent) {
}
public Group(string strAddress, string strName, CBusNode parent)
: base(strAddress , strName, parent) {
}
[XmlArrayItem(El ementName="unit s", Type=typeof(Uni t))]
[XmlArray(Elemen tName="units")]
public Unit[] Units {
get { return m_units;}
set {
// TODO: Add some validation logic here ...
m_units = value;
}
}
}

... and the parent ...

[XmlRootAttribut e(Namespace="", ElementName="LO bject", IsNullable=fals e)]
public abstract class CBusLogicalObje ct : CBusNode
{
public CBusLogicalObje ct() : base()
{
}
public CBusLogicalObje ct(string strAddress, CBusNode parent)
: base(strAddress , parent){
m_address = parent.Address+ "/"+strAddres s;
}
public CBusLogicalObje ct(string strAddress, string strName, CBusNode parent)
: base(strAddress , strName, parent){
m_address = parent.Address+ "/"+strAddres s;
}
}

... and the paren't parent ( don't blame me ... :D )

[XmlRootAttribut e(Namespace="", ElementName="CB usNode", IsNullable=fals e)]
public abstract class CBusNode
{
protected string m_address = null;
protected string m_name = null;
private CBusNode _parent = null;
public CBusNode()
{
}
public CBusNode(string address, CBusNode parent) {
this._parent = parent;
this.m_address = address;
}
public CBusNode(string address, string name, CBusNode parent) {
this._parent = parent;
this.m_address = m_address;
this.m_name = name;
}
[XmlAttributeAtt ribute(Attribut eName="Address" )]
public string Address {
get { return m_address; }
}
[XmlAttributeAtt ribute(Attribut eName="Name")]
public string Name {
get {return m_name; }
}

Thanks a lot for any help,
Cheers,
Angel
O:]
Nov 12 '05 #1
4 9874
Start with easier example such as below. Note private fields will not be
serialized. Public fields and public properties with both get and set will
be. Null fields will also not be serialized by default.

DerivedClass dc = new DerivedClass();
string xml = dc.ToXmlString( );
Console.WriteLi ne(xml);

public class BaseClass
{
public string BaseString = "Hello"; // public.
private string notSerialized; // not xmlserialized as private.
private string base2String = "Happy Holidays"; // property is public.

public BaseClass()
{
notSerialized = "not";
Console.WriteLi ne(notSerialize d); // remove compiler warning.
}

public string Base2String
{
get { return base2String; }
set { base2String = value; } // Both get/set required by xmlseralizer.
}
}

public class DerivedClass : BaseClass
{
private static XmlSerializer ser = new XmlSerializer(t ypeof(DerivedCl ass));

public string DerivedString = "There";

public DerivedClass() : base()
{
}

public string ToXmlString()
{
byte[] bytes = ToBytes(false);
return Encoding.UTF8.G etString(bytes) ;
}

public static DerivedClass FromXmlString(s tring xmlString)
{
if ( xmlString == null )
throw new ArgumentNullExc eption("xmlStri ng");

DerivedClass xr = null;
using(StringRea der sr = new StringReader(xm lString))
{
xr = (DerivedClass)s er.Deserialize( sr);
return xr;
}
}

/// <summary>
/// Serialize class to utf-8 encoded byte array. Serialize defaults to
/// using UTF8 so we can avoid an additional XmlWriter stream.
/// </summary>
/// <param name="prefixLen "></param>
/// <returns></returns>
public byte[] ToBytes(bool prefixLen)
{
using(MemoryStr eam ms = new MemoryStream())
{
if ( prefixLen )
ms.Position = 4;

ser.Serialize(m s, this);

if ( prefixLen )
{
if ( ms.Length > uint.MaxValue )
throw new ArgumentExcepti on("Serialized class bigger then
uint.MaxValue") ;
uint len = (uint)ms.Length ;
byte[] lenBytes = BitConverter.Ge tBytes(len);
ms.Position = 0;
ms.Write(lenByt es, 0, lenBytes.Length );
}
return ms.ToArray();
}
}
}

-- Output --
<?xml version="1.0"?>
<DerivedClass xmlns:xsd="http ://www.w3.org/2001/XMLSchema"
xmlns:xsi="http ://www.w3.org/2001/XMLSchema-instance">
<BaseString>Hel lo</BaseString>
<Base2String>Ha ppy Holidays</Base2String>
<DerivedString> There</DerivedString>
</DerivedClass>

--
William Stacey, MVP
http://mvp.support.microsoft.com

"Angelos Karantzalis" <ak**********@y ahoo.com> wrote in message
news:O2******** ******@TK2MSFTN GP11.phx.gbl...
Hi guys. I've come across a problem when I tried to serialize a class into
xml, only to discover that the parent class's XML Serialization properties
weren't included in the output xml.

Actually, the class I'm serializing is two steps down in the inheritance
ladder. It's got a parent class which also has a parent class :( All those
classes in the hierarchy are Xml Serializable, and I'd think that it should be obvious that all attributes/properties of the parents should be
serialized for any given subclass, no ?
Here's the two classes, subclass first, parent classes afterwards:
[XmlRootAttribut e(Namespace="", ElementName="Gr oup", IsNullable=fals e)]
public class Group : CBusLogicalObje ct
{
private Unit[] m_units = null;
public Group() : base()
{
}
public Group(string strAddress, CBusNode parent)
: base(strAddress , parent) {
}
public Group(string strAddress, string strName, CBusNode parent)
: base(strAddress , strName, parent) {
}
[XmlArrayItem(El ementName="unit s", Type=typeof(Uni t))]
[XmlArray(Elemen tName="units")]
public Unit[] Units {
get { return m_units;}
set {
// TODO: Add some validation logic here ...
m_units = value;
}
}
}

.. and the parent ...

[XmlRootAttribut e(Namespace="", ElementName="LO bject", IsNullable=fals e)]
public abstract class CBusLogicalObje ct : CBusNode
{
public CBusLogicalObje ct() : base()
{
}
public CBusLogicalObje ct(string strAddress, CBusNode parent)
: base(strAddress , parent){
m_address = parent.Address+ "/"+strAddres s;
}
public CBusLogicalObje ct(string strAddress, string strName, CBusNode parent) : base(strAddress , strName, parent){
m_address = parent.Address+ "/"+strAddres s;
}
}

.. and the paren't parent ( don't blame me ... :D )

[XmlRootAttribut e(Namespace="", ElementName="CB usNode", IsNullable=fals e)]
public abstract class CBusNode
{
protected string m_address = null;
protected string m_name = null;
private CBusNode _parent = null;
public CBusNode()
{
}
public CBusNode(string address, CBusNode parent) {
this._parent = parent;
this.m_address = address;
}
public CBusNode(string address, string name, CBusNode parent) {
this._parent = parent;
this.m_address = m_address;
this.m_name = name;
}
[XmlAttributeAtt ribute(Attribut eName="Address" )]
public string Address {
get { return m_address; }
}
[XmlAttributeAtt ribute(Attribut eName="Name")]
public string Name {
get {return m_name; }
}

Thanks a lot for any help,
Cheers,
Angel
O:]


Nov 12 '05 #2
Thanks for the reply Will. I think the original problem was caused because
the "parent's parent" class CBusNode had the Address & Name properties
read-only (no set in the properties). I saw that after I'd send the post,
corrected it, but now I get some very weird exception upon running the test
application, about missing a DLL library with cryptic name - plus it throws
the same exception with a different cryptic dll name every time, as if the
dll name were random!

.... gosh, just when I was saying how nice Xml Serialization is in .NET as
opposed to some Java APIs. Guess again ! :?

Cheers,
Angel
O:]
"William Stacey [MVP]" <st***********@ mvps.org> wrote in message
news:ue******** ******@TK2MSFTN GP12.phx.gbl...
Start with easier example such as below. Note private fields will not be
serialized. Public fields and public properties with both get and set will be. Null fields will also not be serialized by default.

DerivedClass dc = new DerivedClass();
string xml = dc.ToXmlString( );
Console.WriteLi ne(xml);

public class BaseClass
{
public string BaseString = "Hello"; // public.
private string notSerialized; // not xmlserialized as private.
private string base2String = "Happy Holidays"; // property is public.

public BaseClass()
{
notSerialized = "not";
Console.WriteLi ne(notSerialize d); // remove compiler warning.
}

public string Base2String
{
get { return base2String; }
set { base2String = value; } // Both get/set required by xmlseralizer.
}
}

public class DerivedClass : BaseClass
{
private static XmlSerializer ser = new XmlSerializer(t ypeof(DerivedCl ass));
public string DerivedString = "There";

public DerivedClass() : base()
{
}

public string ToXmlString()
{
byte[] bytes = ToBytes(false);
return Encoding.UTF8.G etString(bytes) ;
}

public static DerivedClass FromXmlString(s tring xmlString)
{
if ( xmlString == null )
throw new ArgumentNullExc eption("xmlStri ng");

DerivedClass xr = null;
using(StringRea der sr = new StringReader(xm lString))
{
xr = (DerivedClass)s er.Deserialize( sr);
return xr;
}
}

/// <summary>
/// Serialize class to utf-8 encoded byte array. Serialize defaults to
/// using UTF8 so we can avoid an additional XmlWriter stream.
/// </summary>
/// <param name="prefixLen "></param>
/// <returns></returns>
public byte[] ToBytes(bool prefixLen)
{
using(MemoryStr eam ms = new MemoryStream())
{
if ( prefixLen )
ms.Position = 4;

ser.Serialize(m s, this);

if ( prefixLen )
{
if ( ms.Length > uint.MaxValue )
throw new ArgumentExcepti on("Serialized class bigger then
uint.MaxValue") ;
uint len = (uint)ms.Length ;
byte[] lenBytes = BitConverter.Ge tBytes(len);
ms.Position = 0;
ms.Write(lenByt es, 0, lenBytes.Length );
}
return ms.ToArray();
}
}
}

-- Output --
<?xml version="1.0"?>
<DerivedClass xmlns:xsd="http ://www.w3.org/2001/XMLSchema"
xmlns:xsi="http ://www.w3.org/2001/XMLSchema-instance">
<BaseString>Hel lo</BaseString>
<Base2String>Ha ppy Holidays</Base2String>
<DerivedString> There</DerivedString>
</DerivedClass>

--
William Stacey, MVP
http://mvp.support.microsoft.com

"Angelos Karantzalis" <ak**********@y ahoo.com> wrote in message
news:O2******** ******@TK2MSFTN GP11.phx.gbl...
Hi guys. I've come across a problem when I tried to serialize a class into xml, only to discover that the parent class's XML Serialization properties weren't included in the output xml.

Actually, the class I'm serializing is two steps down in the inheritance
ladder. It's got a parent class which also has a parent class :( All those classes in the hierarchy are Xml Serializable, and I'd think that it

should
be obvious that all attributes/properties of the parents should be
serialized for any given subclass, no ?
Here's the two classes, subclass first, parent classes afterwards:
[XmlRootAttribut e(Namespace="", ElementName="Gr oup", IsNullable=fals e)]
public class Group : CBusLogicalObje ct
{
private Unit[] m_units = null;
public Group() : base()
{
}
public Group(string strAddress, CBusNode parent)
: base(strAddress , parent) {
}
public Group(string strAddress, string strName, CBusNode parent)
: base(strAddress , strName, parent) {
}
[XmlArrayItem(El ementName="unit s", Type=typeof(Uni t))]
[XmlArray(Elemen tName="units")]
public Unit[] Units {
get { return m_units;}
set {
// TODO: Add some validation logic here ...
m_units = value;
}
}
}

.. and the parent ...

[XmlRootAttribut e(Namespace="", ElementName="LO bject", IsNullable=fals e)] public abstract class CBusLogicalObje ct : CBusNode
{
public CBusLogicalObje ct() : base()
{
}
public CBusLogicalObje ct(string strAddress, CBusNode parent)
: base(strAddress , parent){
m_address = parent.Address+ "/"+strAddres s;
}
public CBusLogicalObje ct(string strAddress, string strName, CBusNode

parent)
: base(strAddress , strName, parent){
m_address = parent.Address+ "/"+strAddres s;
}
}

.. and the paren't parent ( don't blame me ... :D )

[XmlRootAttribut e(Namespace="", ElementName="CB usNode", IsNullable=fals e)] public abstract class CBusNode
{
protected string m_address = null;
protected string m_name = null;
private CBusNode _parent = null;
public CBusNode()
{
}
public CBusNode(string address, CBusNode parent) {
this._parent = parent;
this.m_address = address;
}
public CBusNode(string address, string name, CBusNode parent) {
this._parent = parent;
this.m_address = m_address;
this.m_name = name;
}
[XmlAttributeAtt ribute(Attribut eName="Address" )]
public string Address {
get { return m_address; }
}
[XmlAttributeAtt ribute(Attribut eName="Name")]
public string Name {
get {return m_name; }
}

Thanks a lot for any help,
Cheers,
Angel
O:]

Nov 12 '05 #3
> application, about missing a DLL library with cryptic name - plus it
throws
the same exception with a different cryptic dll name every time, as if the
dll name were random!


It is kinda random. A dynamic dll gets created by xmlserializer for your
class. At the moment, I forget why that was necessary or if that step could
be avoided. Would need to see the error message to be sure, but it must be
something to do with issue of serialization or deserialization .

--
William Stacey, MVP
http://mvp.support.microsoft.com
Nov 12 '05 #4
Well, after a whole lot of debugging & playing around & a little help from:
http://weblogs.asp.net/cschittko/articles/33045.aspx I solved the problems.

I just cast the instace being serialized inot the base class in the
XmlSerializer & included the derived classes with an [XmlInclude] attribute
in the parent class.

Thanks for the help William.

Cheers,
Angel
O:]
"William Stacey [MVP]" <st***********@ mvps.org> wrote in message
news:Oz******** *****@TK2MSFTNG P09.phx.gbl...
application, about missing a DLL library with cryptic name - plus it throws
the same exception with a different cryptic dll name every time, as if the dll name were random!


It is kinda random. A dynamic dll gets created by xmlserializer for your
class. At the moment, I forget why that was necessary or if that step

could be avoided. Would need to see the error message to be sure, but it must be something to do with issue of serialization or deserialization .

--
William Stacey, MVP
http://mvp.support.microsoft.com

Nov 12 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2412
by: Gerry Sutton | last post by:
Hi All! I have noticed a strange behavior when using a constant identifier to initialize an instance list variable in a base class and then trying to modifying the list in subclasses by using either the list.extend method or even by having the subclass create a whole new list in the variable. The following example illustrates the...
4
353
by: Angelos Karantzalis | last post by:
Hi guys. I've come across a problem when I tried to serialize a class into xml, only to discover that the parent class's XML Serialization properties weren't included in the output xml. Actually, the class I'm serializing is two steps down in the inheritance ladder. It's got a parent class which also has a parent class :( All those classes...
4
3526
by: MyndPhlyp | last post by:
I am working with Classes in classic VBScript on IIS 5.0 and am having a problem wrapping my head around a solution. I have a Class defining a record layout. (Bear with me here as I completely roach the OOP language.) The objects are columns of the record and each column is defined as its own Class. The record layout class has a method...
1
2073
by: Ivo Bronsveld | last post by:
All, I have quite a challenging task ahead of me. I need to write an object model (for code access) based on a schema, which cannot be made into a dataset because of it's complexity. So I created a couple of objects and serializing it into XML based upon the schema works perfectly. The XML / Schema looks something like this:
5
2642
by: Mark Saccomandi | last post by:
Hi, I'm extending a serializable class I made. The new class adds some features that cannot be serialized automatically, this means that I have to implement the ISerializable interface for my new class. What happens is that I do serialize what I have written within the GetObjectData method, but now I do not get to automatically serialize...
1
1695
by: Derrick | last post by:
Hello all; I seem to be having some trouble serializing a class to XML. This code is a cut & paste from a project which used it perfectly, but all of a sudden I'm getting an error that the "dll ogerh_f6.dll or one of its dependancies cannot be found". The class I'm serializing is quite simple, with a couple of string properties marked...
2
1835
by: Kurious Oranj | last post by:
I've currently got a database structure which is something like:- class a - member type - effective date and:- class b - client name
7
2814
by: fjlaga | last post by:
I have written an Office Add-in for Excel using VB.NET and the .NET 1.1 Framework (I have Visual Studio 2003 .NET ). All works great. I want to add a User Settings/Prefereneces dialog and allow the user to specify some settings and I need to persist these settings between runs. I made a serializable class which uses the BinaryFormatter to...
6
4572
by: Me | last post by:
I need to be able to acces non-virtual members of sublcasses via a base class pointer...and without the need for an explicit type cast. I thought a pure virtual getPtr() that acts as a type cast would solve the problem, but it appears not to. I need this functionality to make object serialization a reality. Having to explicitly cast each...
1
3966
by: jimismint | last post by:
Hi guys, i'm stuck on this problem. only just recently started coding java using blue J. Can you guys help me. import java.util.*; ------------------------------------------------------------------------------------------ public class Player { // the Player class has four fields private int goals; private int height; ...
0
7665
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7888
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6255
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5484
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3643
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1200
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.