473,698 Members | 2,114 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 9900
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
2418
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 situation.
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 in the hierarchy are Xml Serializable, and I'd think that it should be obvious that all...
4
3529
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 called Column(str) that returns the subclass's object. The subclass, in turn, has a Property Get (and...
1
2084
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
2649
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 the data from my parent class. Is there a way to serialize automatically the properties from my...
1
1712
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 with the XmlElementAttribute. The class is marked with the Serializable attribute. As such, I don't...
2
1838
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
2823
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 serialize/deserialize the setttings. Serialization works great. However, when I try to...
6
4594
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 deserialized object to its original type defeats the purpose of my serializing the blasted things in...
1
3971
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; private String name; private int dateofbirth;
0
8674
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9157
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9026
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8893
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7723
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6518
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3045
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2001
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.