473,698 Members | 2,833 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

XmlSerializer for class based on Interface

Hello ,
I have a class which I serialize using XMLSerializer.
This class has public properties which are based on other interfaces.
Because of this I am unable to serialize the object.
Error : There was an error reflecting the type XXXX
Is there any way to serialize this object w/o moving away from Interface
based classes.
Many Thanks!
Eg.
//=========Interf aces=========== ====
public interface IActor
{
[XmlElement("nam e")]
string Name { get; set; }

[XmlElement("age nt")]
IAgent Agent { get; set; }
}

public interface IAgent
{
[XmlElement("rat e")]
double Rate { get; set; }
}
//=========Classe s============== =
[XmlRoot("actor" )]
public class Actor : IActor
{
private string name;

[XmlElement("nam e")]
public string Name
{
get { return name; }
set { name = value; }
}

private IAgent agent;

[XmlElement("bro ker")]
public IAgent Agent
{
get { return agent; }
set { agent = value; }
}

//other customer methods
}

public class Agent : IAgent
{
private double rate;

[XmlElement("rat e")]
public double Rate
{
get { return rate; }
set { rate = value; }
}

}

//============Tes t============== =
[STAThread]
public static void Main()
{
XmlSerializer s;
TextWriter w;

#region actor

IActor actor = new Actor();
actor.Name = "Bob";
IAgent agent = new Agent();
agent.Rate = 12.34D;
actor.Agent = agent;

// Serialization
s = new XmlSerializer(t ypeof (Actor));
w = new StreamWriter(@" c:\list.xml");
s.Serialize(w, actor);
w.Close();

#endregion actor
Console.ReadLin e();
}
Nov 10 '06 #1
3 6537
Give the constructor the typeof(IAgent) too.

Ciaran O'Donnell

"Tantr Mantr" wrote:
Hello ,
I have a class which I serialize using XMLSerializer.
This class has public properties which are based on other interfaces.
Because of this I am unable to serialize the object.
Error : There was an error reflecting the type XXXX
Is there any way to serialize this object w/o moving away from Interface
based classes.
Many Thanks!
Eg.
//=========Interf aces=========== ====
public interface IActor
{
[XmlElement("nam e")]
string Name { get; set; }

[XmlElement("age nt")]
IAgent Agent { get; set; }
}

public interface IAgent
{
[XmlElement("rat e")]
double Rate { get; set; }
}
//=========Classe s============== =
[XmlRoot("actor" )]
public class Actor : IActor
{
private string name;

[XmlElement("nam e")]
public string Name
{
get { return name; }
set { name = value; }
}

private IAgent agent;

[XmlElement("bro ker")]
public IAgent Agent
{
get { return agent; }
set { agent = value; }
}

//other customer methods
}

public class Agent : IAgent
{
private double rate;

[XmlElement("rat e")]
public double Rate
{
get { return rate; }
set { rate = value; }
}

}

//============Tes t============== =
[STAThread]
public static void Main()
{
XmlSerializer s;
TextWriter w;

#region actor

IActor actor = new Actor();
actor.Name = "Bob";
IAgent agent = new Agent();
agent.Rate = 12.34D;
actor.Agent = agent;

// Serialization
s = new XmlSerializer(t ypeof (Actor));
w = new StreamWriter(@" c:\list.xml");
s.Serialize(w, actor);
w.Close();

#endregion actor
Console.ReadLin e();
}

Nov 10 '06 #2
I had to add an additional constructor in additon to the default constructor
as a default is required for serialization.

That did not work. I now get an error : There was an error reflecting type
'Actor'
"Ciaran O''Donnell" wrote:
Give the constructor the typeof(IAgent) too.

Ciaran O'Donnell

"Tantr Mantr" wrote:
Hello ,
I have a class which I serialize using XMLSerializer.
This class has public properties which are based on other interfaces.
Because of this I am unable to serialize the object.
Error : There was an error reflecting the type XXXX
Is there any way to serialize this object w/o moving away from Interface
based classes.
Many Thanks!
Eg.
//=========Interf aces=========== ====
public interface IActor
{
[XmlElement("nam e")]
string Name { get; set; }

[XmlElement("age nt")]
IAgent Agent { get; set; }
}

public interface IAgent
{
[XmlElement("rat e")]
double Rate { get; set; }
}
//=========Classe s============== =
[XmlRoot("actor" )]
public class Actor : IActor
{
private string name;

[XmlElement("nam e")]
public string Name
{
get { return name; }
set { name = value; }
}

private IAgent agent;

[XmlElement("bro ker")]
public IAgent Agent
{
get { return agent; }
set { agent = value; }
}

//other customer methods
}

public class Agent : IAgent
{
private double rate;

[XmlElement("rat e")]
public double Rate
{
get { return rate; }
set { rate = value; }
}

}

//============Tes t============== =
[STAThread]
public static void Main()
{
XmlSerializer s;
TextWriter w;

#region actor

IActor actor = new Actor();
actor.Name = "Bob";
IAgent agent = new Agent();
agent.Rate = 12.34D;
actor.Agent = agent;

// Serialization
s = new XmlSerializer(t ypeof (Actor));
w = new StreamWriter(@" c:\list.xml");
s.Serialize(w, actor);
w.Close();

#endregion actor
Console.ReadLin e();
}
Nov 10 '06 #3
I ran into a similar problem as well. Unforutnately, the default .Net
serializer is not smart enough to pick out the runtime instance of the
interface type. You will have to implement your own serialization routine by
implementing IXmlSerizanble in your class.

A complete listing of your code with IXmlSerializabl e implemented is given
below:

--
Good luck!

Shailen Sukul
Architect
(BSc MCTS, MCSD.Net MCSD MCAD)
Ashlen Consulting Service P/L
(http://www.ashlen.net.au)

using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Xml;
using System.Xml.Seri alization;
using System.IO;

namespace TestConsoleAppl ication
{
//=========Interf aces=========== ====
public interface IActor : IXmlSerializabl e
{
[XmlElement("nam e")]
string Name { get; set; }

[XmlElement("age nt")]
IAgent Agent { get; set; }
}

public interface IAgent : IXmlSerializabl e
{
[XmlElement("rat e")]
double Rate { get; set; }
}
//=========Classe s============== =
[XmlRoot("actor" )]
public class Actor : IActor, IXmlSerializabl e
{
public Actor()
{}

private string name;

[XmlElement("nam e")]
public string Name
{
get { return name; }
set { name = value; }
}

private IAgent agent;

[XmlElement("bro ker")]
public IAgent Agent
{
get { return agent; }
set { agent = value; }
}

//other customer methods

#region IXmlSerializabl e Members

public System.Xml.Sche ma.XmlSchema GetSchema()
{
return null;
}

public void ReadXml(System. Xml.XmlReader reader)
{
name = reader["Name"];

reader.Read(); // Skip ahead to next node

if (reader.MoveToC ontent() == XmlNodeType.Ele ment &&
reader.LocalNam e == "broker")
{
agent = new Agent();
agent.ReadXml(r eader);
}
}

public void WriteXml(System .Xml.XmlWriter writer)
{
writer.WriteAtt ributeString("N ame", Name);

writer.WriteSta rtElement("brok er");
agent.WriteXml( writer);
writer.WriteEnd Element();

}

#endregion
}

public class Agent : IAgent, IXmlSerializabl e
{
private double rate;

[XmlElement("rat e")]
public double Rate
{
get { return rate; }
set { rate = value; }
}

#region IXmlSerializabl e Members

public System.Xml.Sche ma.XmlSchema GetSchema()
{
return null;
}

public void ReadXml(System. Xml.XmlReader reader)
{
rate = double.Parse(re ader["rate"]);
}

public void WriteXml(System .Xml.XmlWriter writer)
{
writer.WriteAtt ributeString("r ate", rate.ToString() );
}

#endregion
}

class test
{
//============Tes t============== =
[STAThread]
public static void Main()
{
XmlSerializer s;
TextWriter w;

#region actor

IActor actor = new Actor();
actor.Name = "Bob";
IAgent agent = new Agent();
agent.Rate = 12.34D;
actor.Agent = agent;

// Serialization
s = new XmlSerializer(t ypeof(Actor));
w = new StreamWriter(@" c:\list.xml");
s.Serialize(w, actor);
w.Close();

// deserialize
XmlSerializer xs = new XmlSerializer(t ypeof(Actor));
FileStream fs = new FileStream(@"c: \\list.xml", FileMode.Open);
fs.Position = 0;
IActor actor2 = (Actor)xs.Deser ialize(fs);
Console.WriteLi ne(string.Forma t("Actor Name = {0} Broker.Rate =
{1}", actor2.Name, actor2.Agent.Ra te));

#endregion actor
Console.ReadLin e();
}
}
}

Nov 12 '06 #4

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

Similar topics

5
5423
by: Stuart Robertson | last post by:
I am trying to find a solution that will allow me to use XmlSerializer to serialize/deserialize a collection of objects where a given object is shared between two or more other objects, and not create duplicate XML representations of the shared object, but instead use IDREFs to refer to the shared object. The XML I'm trying to produce is as follows (where "href" is an IDREF): <?xml version="1.0" encoding="utf-8"?> <MyRootClass...
3
7000
by: Anthony Bouch | last post by:
Hi I've been reading using the XmlSerializer with custom collections. I've discovered that when serializing a custom collection (a class that implements ICollection, IList etc.) the XmlSerializer will only serialize the collection items - with the default root as ArrayofMyItems etc. My custom collection class has some additional public properties that I would like to include in the serialization above the items element array (in
4
11387
by: Andy Neilson | last post by:
I've run across a strange behaviour with XmlSerializer that I'm unable to explain. I came across this while trying to use XmlSerializer to deserialize from a the details of a SoapException. This should have worked fine since the class in question was already being serialized and deserialized as part of a Web service interface. What I found was that by deserializing from an XmlNodeReader instead of an XmlTextReader, XML Serialization doesn't work...
3
9032
by: Bob Rundle | last post by:
I'm trying to serialize a class with XmlSerializer. This class implements the IEnumerable interface. I implemented the IEnumerable interface for reasons other than Xml serialization. However I find that the XmlSerializer, because I have an IEnumerable interface on this class, wants to ignore the public properties of this class and simply serialize an array of objects. I wand XmlSerializer to ignore the IEnumerable interface that I...
1
5947
by: Vladimir Semenov | last post by:
Hi, I'm trying to serialize a type contained in assembly referering to another assembly in GAC. XmlSerializer xs = new XmlSerializer( typeof(TransferParentData ) ); The code above throws exception: System.IO.FileNotFoundException : File or assembly name rng0i4ly.dll, or one of its dependencies, was not found. at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Boolean isStringized, Evidence assemblySecurity,...
3
3168
by: Don McNamara | last post by:
Hi, I've hit quite a strange problem with XmlSerializer on my W2K3 server. When I serialize/deserialize using an exe on my local computer (XP), everything works fine. When I put the code out on the server (W2K3) it throws an exception. It only seems to happen when serializing/deserializing _arrays_ of a type. If I just serialize/deserialize one instance, it works fine. The exception I get is: (sorry for the word wrapping.)...
6
5188
by: preport | last post by:
I have a webservice that returns data from a database. Our services (the clients) have been blowing up because of illegal character problems. Is there anything I can do on the server side to work around this problem. I'm OK with deleting all the "bad" characters. I have a couple DTOs that are marked with that I return from the web service after they're populated with data from the database. Is there some kind of attribute or...
10
4780
by: Henrik Dahl | last post by:
Hello! I have an xml schema which has a date typed attribute. I have used xsd.exe to create a class library for XmlSerializer. The result of XmlSerializer.Serialize(...) should be passed as the value for the parameter of an SqlCommand for inserting the xml document in a column of a table where the column is typed to be of the same xml schema. This all sounds simple, but SQL Server REQUIRES the timezone to be specified for date values....
1
406
by: =?iso-8859-2?Q?S=B3awomir_Krzy=BFanowski?= | last post by:
When I execute this code everything works fine, no exception is throwed. Method GetObjectData was not entered, but object was serialized and file cos.xml was created with correct data. When I use BinaryFormater then Exception(" That metod... is throwed. I don't know why GetObjectData is not executed with XmlSerializer. FileStream stream = new FileStream(@"d:\cos.xml", FileMode.Open, FileAccess.ReadWrite); XmlSerializerFactory...
0
8611
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9170
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
9031
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
8904
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
8876
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7741
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...
0
4372
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3052
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
2007
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.