473,378 Members | 1,631 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

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:
[XmlRootAttribute(Namespace="", ElementName="Group", IsNullable=false)]
public class Group : CBusLogicalObject
{
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(ElementName="units", Type=typeof(Unit))]
[XmlArray(ElementName="units")]
public Unit[] Units {
get { return m_units;}
set {
// TODO: Add some validation logic here ...
m_units = value;
}
}
}

... and the parent ...

[XmlRootAttribute(Namespace="", ElementName="LObject", IsNullable=false)]
public abstract class CBusLogicalObject : CBusNode
{
public CBusLogicalObject() : base()
{
}
public CBusLogicalObject(string strAddress, CBusNode parent)
: base(strAddress, parent){
m_address = parent.Address+"/"+strAddress;
}
public CBusLogicalObject(string strAddress, string strName, CBusNode parent)
: base(strAddress, strName, parent){
m_address = parent.Address+"/"+strAddress;
}
}

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

[XmlRootAttribute(Namespace="", ElementName="CBusNode", IsNullable=false)]
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;
}
[XmlAttributeAttribute(AttributeName="Address")]
public string Address {
get { return m_address; }
}
[XmlAttributeAttribute(AttributeName="Name")]
public string Name {
get {return m_name; }
}

Thanks a lot for any help,
Cheers,
Angel
O:]
Nov 12 '05 #1
4 9817
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.WriteLine(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.WriteLine(notSerialized); // 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(typeof(DerivedClass));

public string DerivedString = "There";

public DerivedClass() : base()
{
}

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

public static DerivedClass FromXmlString(string xmlString)
{
if ( xmlString == null )
throw new ArgumentNullException("xmlString");

DerivedClass xr = null;
using(StringReader sr = new StringReader(xmlString))
{
xr = (DerivedClass)ser.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(MemoryStream ms = new MemoryStream())
{
if ( prefixLen )
ms.Position = 4;

ser.Serialize(ms, this);

if ( prefixLen )
{
if ( ms.Length > uint.MaxValue )
throw new ArgumentException("Serialized class bigger then
uint.MaxValue");
uint len = (uint)ms.Length;
byte[] lenBytes = BitConverter.GetBytes(len);
ms.Position = 0;
ms.Write(lenBytes, 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>Hello</BaseString>
<Base2String>Happy Holidays</Base2String>
<DerivedString>There</DerivedString>
</DerivedClass>

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

"Angelos Karantzalis" <ak**********@yahoo.com> wrote in message
news:O2**************@TK2MSFTNGP11.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:
[XmlRootAttribute(Namespace="", ElementName="Group", IsNullable=false)]
public class Group : CBusLogicalObject
{
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(ElementName="units", Type=typeof(Unit))]
[XmlArray(ElementName="units")]
public Unit[] Units {
get { return m_units;}
set {
// TODO: Add some validation logic here ...
m_units = value;
}
}
}

.. and the parent ...

[XmlRootAttribute(Namespace="", ElementName="LObject", IsNullable=false)]
public abstract class CBusLogicalObject : CBusNode
{
public CBusLogicalObject() : base()
{
}
public CBusLogicalObject(string strAddress, CBusNode parent)
: base(strAddress, parent){
m_address = parent.Address+"/"+strAddress;
}
public CBusLogicalObject(string strAddress, string strName, CBusNode parent) : base(strAddress, strName, parent){
m_address = parent.Address+"/"+strAddress;
}
}

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

[XmlRootAttribute(Namespace="", ElementName="CBusNode", IsNullable=false)]
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;
}
[XmlAttributeAttribute(AttributeName="Address")]
public string Address {
get { return m_address; }
}
[XmlAttributeAttribute(AttributeName="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**************@TK2MSFTNGP12.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.WriteLine(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.WriteLine(notSerialized); // 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(typeof(DerivedClass));
public string DerivedString = "There";

public DerivedClass() : base()
{
}

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

public static DerivedClass FromXmlString(string xmlString)
{
if ( xmlString == null )
throw new ArgumentNullException("xmlString");

DerivedClass xr = null;
using(StringReader sr = new StringReader(xmlString))
{
xr = (DerivedClass)ser.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(MemoryStream ms = new MemoryStream())
{
if ( prefixLen )
ms.Position = 4;

ser.Serialize(ms, this);

if ( prefixLen )
{
if ( ms.Length > uint.MaxValue )
throw new ArgumentException("Serialized class bigger then
uint.MaxValue");
uint len = (uint)ms.Length;
byte[] lenBytes = BitConverter.GetBytes(len);
ms.Position = 0;
ms.Write(lenBytes, 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>Hello</BaseString>
<Base2String>Happy Holidays</Base2String>
<DerivedString>There</DerivedString>
</DerivedClass>

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

"Angelos Karantzalis" <ak**********@yahoo.com> wrote in message
news:O2**************@TK2MSFTNGP11.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:
[XmlRootAttribute(Namespace="", ElementName="Group", IsNullable=false)]
public class Group : CBusLogicalObject
{
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(ElementName="units", Type=typeof(Unit))]
[XmlArray(ElementName="units")]
public Unit[] Units {
get { return m_units;}
set {
// TODO: Add some validation logic here ...
m_units = value;
}
}
}

.. and the parent ...

[XmlRootAttribute(Namespace="", ElementName="LObject", IsNullable=false)] public abstract class CBusLogicalObject : CBusNode
{
public CBusLogicalObject() : base()
{
}
public CBusLogicalObject(string strAddress, CBusNode parent)
: base(strAddress, parent){
m_address = parent.Address+"/"+strAddress;
}
public CBusLogicalObject(string strAddress, string strName, CBusNode

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

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

[XmlRootAttribute(Namespace="", ElementName="CBusNode", IsNullable=false)] 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;
}
[XmlAttributeAttribute(AttributeName="Address")]
public string Address {
get { return m_address; }
}
[XmlAttributeAttribute(AttributeName="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*************@TK2MSFTNGP09.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
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...
4
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. ...
4
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...
1
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...
5
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...
1
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...
2
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
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...
6
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...
1
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.*;...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.