473,750 Members | 2,186 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Serializing descendants of generic collections

Can anyone explain why the following program doesn't work? The
attributes and elements of the MessageList class are not being
generated.

Am I doing something incorrectly? Or if this is a bug in .NET, is
there a known workaround?

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

[Serializable, XmlRoot("Messag e")]
public class Message
{
private int _id;
private string _description;

[XmlAttribute("i d")]
public int Id
{
get { return _id; }
set { _id = value; }
}

[XmlElement("Des cription")]
public string Description
{
get { return _description; }
set { _description = value; }
}
}

[Serializable, XmlRoot("Messag eList")]
public class MessageList : List<Message>
{
private int _id;
private string _name = "";

[XmlAttribute("i d")]
public int Id
{
get { return _id; }
set { _id = value; }
}

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

public class Program
{
public static void Main()
{
Program test = new Program();

Message m1 = new Message();
m1.Id = 1;
m1.Description = "Message 1";

Message m2 = new Message();
m2.Id = 2;
m2.Description = "Message 2";

MessageList messageList = new MessageList();

messageList.Add (m1);
messageList.Add (m2);

messageList.Id = 20070822;

test.Serialize( messageList);

Console.ReadLin e();
}

private void Serialize<T>(T obj)
{
string xml;
XmlSerializer serializer = new XmlSerializer(t ypeof(T));

using (MemoryStream memoryStream = new MemoryStream())
{
using (XmlTextWriter xmlTextWriter = new
XmlTextWriter(m emoryStream, Encoding.UTF8))
{
xmlTextWriter.F ormatting = Formatting.Inde nted;

serializer.Seri alize(xmlTextWr iter, obj);
xml =
Encoding.UTF8.G etString(((Memo ryStream)xmlTex tWriter.BaseStr eam).ToArray()) .Trim();
}
}

Console.WriteLi ne(xml);
}
}

Aug 22 '07 #1
2 3558
OK I found out that it's not really supported:
http://msdn2.microsoft.com/en-us/library/182eeyhh.aspx

Does anyone know of a suitable workaround?

ilitirit wrote:
Can anyone explain why the following program doesn't work? The
attributes and elements of the MessageList class are not being
generated.

Am I doing something incorrectly? Or if this is a bug in .NET, is
there a known workaround?
Aug 22 '07 #2
Hi ilitirit, you could try this as a work-a-round:

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

[Serializable, XmlRoot("Messag e")]
public class Message
{
private int _id;
private string _description;

[XmlAttribute("i d")]
public int Id
{
get { return _id; }
set { _id = value; }
}

[XmlElement("Des cription")]
public string Description
{
get { return _description; }
set { _description = value; }
}
}

[Serializable, XmlRoot("Messag eList")]
public class MessageList : List<Message>, IXmlSerializabl e
{
private int _id;
private string _name = "";

[XmlAttribute("i d")]
public int Id
{
get { return _id; }
set { _id = value; }
}

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

#region IXmlSerializabl e Members

public System.Xml.Sche ma.XmlSchema GetSchema()
{
throw new Exception("The method or operation is not implemented.");
}

public void ReadXml(XmlRead er reader)
{
throw new Exception("The method or operation is not implemented.");
}

public void WriteXml(XmlWri ter writer)
{
writer.WriteSta rtAttribute("Me ssageListId");
writer.WriteVal ue(this.Id.ToSt ring());
writer.WriteEnd Attribute();

writer.WriteSta rtAttribute("Me ssageListName") ;
writer.WriteVal ue(this.Name);
writer.WriteEnd Attribute();

foreach (Message msg in this)
{
XmlSerializer serializer = new XmlSerializer(t ypeof(Message)) ;
serializer.Seri alize(writer, msg);
}
}

#endregion
}

public class Program
{
public static void Main()
{
Program test = new Program();

Message m1 = new Message();
m1.Id = 1;
m1.Description = "Message 1";

Message m2 = new Message();
m2.Id = 2;
m2.Description = "Message 2";

MessageList messageList = new MessageList();

messageList.Add (m1);
messageList.Add (m2);

messageList.Id = 20070822;

test.Serialize( messageList);

Console.ReadLin e();
}

private void Serialize<T>(T obj)
{
string xml;
XmlSerializer serializer = new XmlSerializer(t ypeof(T));

using (MemoryStream memoryStream = new MemoryStream())
{
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(m emoryStream,
Encoding.UTF8))
{
xmlTextWriter.F ormatting = Formatting.Inde nted;

serializer.Seri alize(xmlTextWr iter, obj);
xml =
Encoding.UTF8.G etString(((Memo ryStream)xmlTex tWriter.BaseStr eam).ToArray()) .Trim();
}
}

Console.WriteLi ne(xml);
}
}
"ilitirit" wrote:
OK I found out that it's not really supported:
http://msdn2.microsoft.com/en-us/library/182eeyhh.aspx

Does anyone know of a suitable workaround?

ilitirit wrote:
Can anyone explain why the following program doesn't work? The
attributes and elements of the MessageList class are not being
generated.

Am I doing something incorrectly? Or if this is a bug in .NET, is
there a known workaround?

Aug 31 '07 #3

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

Similar topics

1
2087
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:
2
2034
by: Jasper Kent | last post by:
I'm trying to do the equivalent of using typedefs with templates in C++ to avoid long instantiation names. I can do this okay: using BigDictionary = System.Collections.Generic.Dictionary<int, System.Collections.Generic.Dictionary<int, string>>; class MyClass {
3
11757
by: RandomEngineer | last post by:
So here's the challenge... How can a collection (System.Collections.Generic.IList) of some custom type be serialized in a web service using .NET 2.0? Below are the class and the web methods in question. The interesting thing is that at each step of the way, DAL & Biz, the someType class is decorated with the Serializable attribute. And the someTypes collection in the web method is correctly populated with the data after the call to...
3
5107
by: KH | last post by:
I can't seem to figure this one out... I've searched MSDN and Goog, and made my best guesses to no avail,, so help would be much appreciated! public ref class T sealed : public System::Collections::IEnumerable , public System::Collections::Generic::IEnumerable<int> { // How to implement GetEnumerator() for both interfaces? // Compiler complains that functions differ only in return type // which I understand, but can't get the right...
1
831
by: Peter Nofelt | last post by:
Hey All, I am having issue with serializing a class and its base class using ..net 2.0. I am using IXmlSerializable I've provided code displaying my at the bottom of this post. Thanks ahead of time for any help or feedback. Cheers, Peter
0
2276
by: Kurious Oranj | last post by:
This is the code that I currently have written to serialize the collection but it doesn't work when I put two "child" objects in. Anyone have any ideas what I'm doing wrong? ------------------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Text; using System.Collections;
2
7361
by: Fred Heida | last post by:
Hi, i'm trying to (using managed C++) implment the IEnumerable<Tinterface on my class.. but have a problem with the 2 GetEnumerator method required.... what i have done is... generic<typename T> public ref class SetOfProxy : public System::Collections::Generic::IEnumerable<T>
5
4190
by: Michi Henning | last post by:
I can pass a generic collection as ICollection<Tjust fine: static void flatCollection(ICollection<intc) {} // ... List<intl = new List<int>(); flatCollection(l); // Works fine Now I want to pass nested collections generically:
2
4183
by: SimonDotException | last post by:
I am trying to use reflection in a property of a base type to inspect the properties of an instance of a type which is derived from that base type, when the properties can themselves be instances of types derived from that base type, or arrays or generic collections of instances of types derived from that base type. All is well until I come to the properties which are generic collections, I don't seem to be able to find an elegant way of...
0
8999
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
8836
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
9575
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
9394
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
9338
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
6080
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();...
0
4712
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
3322
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
2
2798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.