473,323 Members | 1,547 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,323 software developers and data experts.

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.
//=========Interfaces===============
public interface IActor
{
[XmlElement("name")]
string Name { get; set; }

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

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

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

private IAgent agent;

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

//other customer methods
}

public class Agent : IAgent
{
private double rate;

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

}

//============Test===============
[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(typeof (Actor));
w = new StreamWriter(@"c:\list.xml");
s.Serialize(w, actor);
w.Close();

#endregion actor
Console.ReadLine();
}
Nov 10 '06 #1
3 6508
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.
//=========Interfaces===============
public interface IActor
{
[XmlElement("name")]
string Name { get; set; }

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

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

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

private IAgent agent;

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

//other customer methods
}

public class Agent : IAgent
{
private double rate;

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

}

//============Test===============
[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(typeof (Actor));
w = new StreamWriter(@"c:\list.xml");
s.Serialize(w, actor);
w.Close();

#endregion actor
Console.ReadLine();
}

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.
//=========Interfaces===============
public interface IActor
{
[XmlElement("name")]
string Name { get; set; }

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

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

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

private IAgent agent;

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

//other customer methods
}

public class Agent : IAgent
{
private double rate;

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

}

//============Test===============
[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(typeof (Actor));
w = new StreamWriter(@"c:\list.xml");
s.Serialize(w, actor);
w.Close();

#endregion actor
Console.ReadLine();
}
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 IXmlSerializable 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.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace TestConsoleApplication
{
//=========Interfaces===============
public interface IActor : IXmlSerializable
{
[XmlElement("name")]
string Name { get; set; }

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

public interface IAgent : IXmlSerializable
{
[XmlElement("rate")]
double Rate { get; set; }
}
//=========Classes===============
[XmlRoot("actor")]
public class Actor : IActor, IXmlSerializable
{
public Actor()
{}

private string name;

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

private IAgent agent;

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

//other customer methods

#region IXmlSerializable Members

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

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

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

if (reader.MoveToContent() == XmlNodeType.Element &&
reader.LocalName == "broker")
{
agent = new Agent();
agent.ReadXml(reader);
}
}

public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteAttributeString("Name", Name);

writer.WriteStartElement("broker");
agent.WriteXml(writer);
writer.WriteEndElement();

}

#endregion
}

public class Agent : IAgent, IXmlSerializable
{
private double rate;

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

#region IXmlSerializable Members

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

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

public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteAttributeString("rate", rate.ToString());
}

#endregion
}

class test
{
//============Test===============
[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(typeof(Actor));
w = new StreamWriter(@"c:\list.xml");
s.Serialize(w, actor);
w.Close();

// deserialize
XmlSerializer xs = new XmlSerializer(typeof(Actor));
FileStream fs = new FileStream(@"c:\\list.xml", FileMode.Open);
fs.Position = 0;
IActor actor2 = (Actor)xs.Deserialize(fs);
Console.WriteLine(string.Format("Actor Name = {0} Broker.Rate =
{1}", actor2.Name, actor2.Agent.Rate));

#endregion actor
Console.ReadLine();
}
}
}

Nov 12 '06 #4

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

Similar topics

5
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...
3
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...
4
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...
3
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...
1
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...
3
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...
6
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...
10
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...
1
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...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.