How to XMLSerialize Collection Class

Hi,

I have a collection class where I've implemeneted the 
ICollection Interface.

Here is a small code segment.

public class PageList : ICollection, IComparer, 
IEnumerable, IList
{
		protected ArrayList _pages;

		public PageList()
		{
			_pages = new ArrayList();
		}


		#region IList Members


		public object this[int index]
		{
			get
			{
				if (index > _pages.Count)
				{
					return (Page)null;
				}
				else
				{
					return (Page)_pages
[index];
				}
			}
			set
			{
			}
		}

		public int Add(object objPage)
		{

			int arrayIndexAdded = -1;
			arrayIndexAdded = _pages.Add
(objPage);
			return arrayIndexAdded;
		}

}

I have another class which declares this PageList class 
and creates an instance of it.  

How do I serialized this class?


0
anonymous (74721)
11/28/2003 11:38:09 PM
dotnet.xml 7266 articles. 0 followers. Follow

3 Replies
777 Views

Similar Articles

[PageSpeed] 30

Hman,

You should be able to serialize instances like this:

PageList pl = new PageList();

// populate pl

XmlSerializer ser = new XmlSerializer( typeof( PageList ), new Type[] {
 ... } ); // enumerate all the types in the list.
ser.Serialize( writer, pl );

be careful though ... if you don't know what the types in your List are,
then getting the Types from the list elements and instantiating a serializer
instance is a very expensive operation and if performance matters, then you
should probably alter your design to not go that route.

I also have a few questions about the PageList class. Why do you implement
everything by hand, is there any reason you don't derive from CollectionBase
or ? And why are you even implementing a custom List if you don't strongly
type it? You may just as well stick to the ArrayList.

-- 
HTH
Christoph Schittko [MVP, XmlInsider]
Software Architect, .NET Mentor
"hman" <anonymous@discussions.microsoft.com> wrote in message
news:08d001c3b608$ae35c960$a001280a@phx.gbl...
> Hi,
>
> I have a collection class where I've implemeneted the
> ICollection Interface.
>
> Here is a small code segment.
>
> public class PageList : ICollection, IComparer,
> IEnumerable, IList
> {
> protected ArrayList _pages;
>
> public PageList()
> {
> _pages = new ArrayList();
> }
>
>
> #region IList Members
>
>
> public object this[int index]
> {
> get
> {
> if (index > _pages.Count)
> {
> return (Page)null;
> }
> else
> {
> return (Page)_pages
> [index];
> }
> }
> set
> {
> }
> }
>
> public int Add(object objPage)
> {
>
> int arrayIndexAdded = -1;
> arrayIndexAdded = _pages.Add
> (objPage);
> return arrayIndexAdded;
> }
>
> }
>
> I have another class which declares this PageList class
> and creates an instance of it.
>
> How do I serialized this class?
>
>


0
11/29/2003 1:36:38 AM
Hi, thanks for your help.


Actually, I have another class (Survey) which has an 
instance of my PageList class.

code segment:

public class Survey 
{
//survey has a collection of pages 
private PageList _pagesCol;
private Page _currentPage;

  public Survey()
  {
   _pagesCol = new PageList();
   Page defaultFirstPage = new Page();
   defaultFirstPage.Name = "Page 1";
   _pagesCol.Add (defaultFirstPage);
  }

}

I am simply serializing an intance of Survey:

// Serialization
XmlSerializer s = new XmlSerializer(typeof(Survey));
TextWriter w = new StreamWriter(@"C:\SCSurvey.xml");
s.Serialize(w, _survey);
w.Close();

where _survey is my Survey instance created elsewhere.
Why isn't my PageList intance serialized?


-
-I don't know what strongly types custom lists are.


>-----Original Message-----
>Hman,
>
>You should be able to serialize instances like this:
>
>PageList pl = new PageList();
>
>// populate pl
>
>XmlSerializer ser = new XmlSerializer( typeof( 
PageList ), new Type[] {
> ... } ); // enumerate all the types in the list.
>ser.Serialize( writer, pl );
>
>be careful though ... if you don't know what the types in 
your List are,
>then getting the Types from the list elements and 
instantiating a serializer
>instance is a very expensive operation and if performance 
matters, then you
>should probably alter your design to not go that route.
>
>I also have a few questions about the PageList class. Why 
do you implement
>everything by hand, is there any reason you don't derive 
from CollectionBase
>or ? And why are you even implementing a custom List if 
you don't strongly
>type it? You may just as well stick to the ArrayList.
>
>-- 
>HTH
>Christoph Schittko [MVP, XmlInsider]
>Software Architect, .NET Mentor
>"hman" <anonymous@discussions.microsoft.com> wrote in 
message
>news:08d001c3b608$ae35c960$a001280a@phx.gbl...
>> Hi,
>>
>> I have a collection class where I've implemeneted the
>> ICollection Interface.
>>
>> Here is a small code segment.
>>
>> public class PageList : ICollection, IComparer,
>> IEnumerable, IList
>> {
>> protected ArrayList _pages;
>>
>> public PageList()
>> {
>> _pages = new ArrayList();
>> }
>>
>>
>> #region IList Members
>>
>>
>> public object this[int index]
>> {
>> get
>> {
>> if (index > _pages.Count)
>> {
>> return (Page)null;
>> }
>> else
>> {
>> return (Page)_pages
>> [index];
>> }
>> }
>> set
>> {
>> }
>> }
>>
>> public int Add(object objPage)
>> {
>>
>> int arrayIndexAdded = -1;
>> arrayIndexAdded = _pages.Add
>> (objPage);
>> return arrayIndexAdded;
>> }
>>
>> }
>>
>> I have another class which declares this PageList class
>> and creates an instance of it.
>>
>> How do I serialized this class?
>>
>>
>
>
>.
>
0
anonymous (74721)
11/29/2003 4:48:26 PM
Got everything working.  Thanks.

>-----Original Message-----
>Hi, thanks for your help.
>
>
>Actually, I have another class (Survey) which has an 
>instance of my PageList class.
>
>code segment:
>
>public class Survey 
>{
>//survey has a collection of pages 
>private PageList _pagesCol;
>private Page _currentPage;
>
>  public Survey()
>  {
>   _pagesCol = new PageList();
>   Page defaultFirstPage = new Page();
>   defaultFirstPage.Name = "Page 1";
>   _pagesCol.Add (defaultFirstPage);
>  }
>
>}
>
>I am simply serializing an intance of Survey:
>
>// Serialization
>XmlSerializer s = new XmlSerializer(typeof(Survey));
>TextWriter w = new StreamWriter(@"C:\SCSurvey.xml");
>s.Serialize(w, _survey);
>w.Close();
>
>where _survey is my Survey instance created elsewhere.
>Why isn't my PageList intance serialized?
>
>
>-
>-I don't know what strongly types custom lists are.
>
>
>>-----Original Message-----
>>Hman,
>>
>>You should be able to serialize instances like this:
>>
>>PageList pl = new PageList();
>>
>>// populate pl
>>
>>XmlSerializer ser = new XmlSerializer( typeof( 
>PageList ), new Type[] {
>> ... } ); // enumerate all the types in the list.
>>ser.Serialize( writer, pl );
>>
>>be careful though ... if you don't know what the types 
in 
>your List are,
>>then getting the Types from the list elements and 
>instantiating a serializer
>>instance is a very expensive operation and if 
performance 
>matters, then you
>>should probably alter your design to not go that route.
>>
>>I also have a few questions about the PageList class. 
Why 
>do you implement
>>everything by hand, is there any reason you don't derive 
>from CollectionBase
>>or ? And why are you even implementing a custom List if 
>you don't strongly
>>type it? You may just as well stick to the ArrayList.
>>
>>-- 
>>HTH
>>Christoph Schittko [MVP, XmlInsider]
>>Software Architect, .NET Mentor
>>"hman" <anonymous@discussions.microsoft.com> wrote in 
>message
>>news:08d001c3b608$ae35c960$a001280a@phx.gbl...
>>> Hi,
>>>
>>> I have a collection class where I've implemeneted the
>>> ICollection Interface.
>>>
>>> Here is a small code segment.
>>>
>>> public class PageList : ICollection, IComparer,
>>> IEnumerable, IList
>>> {
>>> protected ArrayList _pages;
>>>
>>> public PageList()
>>> {
>>> _pages = new ArrayList();
>>> }
>>>
>>>
>>> #region IList Members
>>>
>>>
>>> public object this[int index]
>>> {
>>> get
>>> {
>>> if (index > _pages.Count)
>>> {
>>> return (Page)null;
>>> }
>>> else
>>> {
>>> return (Page)_pages
>>> [index];
>>> }
>>> }
>>> set
>>> {
>>> }
>>> }
>>>
>>> public int Add(object objPage)
>>> {
>>>
>>> int arrayIndexAdded = -1;
>>> arrayIndexAdded = _pages.Add
>>> (objPage);
>>> return arrayIndexAdded;
>>> }
>>>
>>> }
>>>
>>> I have another class which declares this PageList class
>>> and creates an instance of it.
>>>
>>> How do I serialized this class?
>>>
>>>
>>
>>
>>.
>>
>.
>
0
anonymous (74721)
11/29/2003 8:36:17 PM
Reply:

Similar Artilces:

XmlSerializer Collection with Collections
Hello I got this working but it is not how I really want it, basically I have an xml file which has a root of <test> and can be filled with 3 different types of <question> elements with different attributes, all share a base set of 4, one of the question types can have children with <option> elements, this is how the xml looks after serialization.... If you notice there is an extra <SelectionList> around the <option>'s in the final <question>, how can I write my class so I don't have this extra <SelectionList> element....my class follows, you ...

Employee Class in Payroll
The concept of using employee classes is a great idea however; the functionality is somewhat limited and confusing to users. The way I have been using it is to only assign a mass of pay codes. My question is, is there a way to shutoff the functionality of overwriting position, department, deductions, etc and just the assigment of pay codes? Has anyone modified the functionality or is it even possible? Thanks! It should not be confusing. It serves two functions: reporting and employee additions/maintenance. You should always use it before you enter any other data about the employee. ...

XmlSerializer
I'm having a basic problem with the XmlSerializer & i'm at my wits end trying to sort it out i have a basic clas <Serializable()> Class Tes Public Name as Strin End Clas when this serializes i wan <Test><Name>Value</Name></Test the problem is if i use the XmlSerializer clas Dim t as Tes t.Name="Value Dim sb As New StringBuilde Dim sw As New StringWriter(sb Dim Serializer As New XmlSerializer(Message.GetType Serializer.Serialize(sw, t Serializer = Nothin Console.Write(sb.ToStr...

Build error when adding a message handler to a CWinThread derived class
This one might be simple, but I'm scratching my head a bit. I've got a class derived from CWinThread, and when I want it to do something I'll post a message to it MyWinThreadObj->PostThreadMessage(MyMessage, param1, param2); and declare a function handler as public or protected or whatever LRESULT Handler(WPARAM, LPARAM); and in the message map for the class : BEGIN_MESSAGE_MAP(MyClass, CWinThread) ON_MESSAGE(WM_MYMESSAGE,Handler) END_MESSAGE_MAP() and the compliler is telling me: error C2440: 'static_cast' : cannot convert from 'LRESULT (__thiscall MyClass...

Collecting data through email using VBA
Hi, I know that the "Create Email" tool in order to collect data through email but I want to do it automatically. My database form includes VBA code in order to send automate emails. I'd like to make this email "special" in order to receive the replay into access and use the answer email. I'd be grateful if someone could help me with the VBA code. Thanks! This capability is included in Access 2007, if you are using the .accdb file format, although you still need to initiate the process (ie. it is not fully automatic). What version of Access are you using? ...

Returning classes with pointers to buffers
I have been curious about this for a while. When we return a class variable containing a pointer to a buffer, what happens to the contents of the buffer? To illustrate what I mean, let me consider: CString A( _T("This is the data") ); CString B(A); A and B both contain pointers to an actual array of characters, but A and B are completely independent, and so B must create its own copy of the actual data - the TCHARs "This is the data". So far so good. However if we have CString Function( ) { CString A; // ..... A = _T("This is the data") ;...

problem with Class wizard
I've just upgraded to Visual studio 2003 from VC6 Everything seems fine except for dialog boxes and Class Wizard If I make a new dialog box, then double click on it - up comes the wizard I give a name to the CPP and H files as normal and press Finish But the code is NOT made, so I cannot do anything with the dialog It worked fine with VC6.0 Does anyone know what may be happening here Any help will be much appreciated Phil "phil" <phil@oakleafsoftware.co.nospam> wrote in message news:#IxHP1DjFHA.1232@TK2MSFTNGP15.phx.gbl... > > Does anyone know what may be happ...

XmlSerializer and shared objects (or How to generate IDREFs using XmlSerializer)
This is a multi-part message in MIME format. ------=_NextPart_000_007F_01C34AC1.11D4FB20 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable 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): <...

Some stock trader is giving a free class
This guy I've been following, the stock stalker, absolutely nailed GNBT right at the bottom. Now it looks like he is giving a free charting class on how he pulled it off. Thought you traders might want to check it out. http://www.thestockstalker.com/primer.html?osadcampaign=fwg ...

Manually Data Collection
In Manufacturing we are doing Manually DC to get information about Ok an Rejection work on each and every opertation with in a Routing. During this process i found that DC Activity not attached with my MO, for exemple 1. I can enter any qty in Piece Ok or Rejected fields even if the Mo Qty 100 but for the same MO Data Collection can be done for 1000pcs. 2. In data collection form no information about MO Quantities. 3. As my operations are based on piece work bases and each operation in routing have diffrent rates as well labor, so when I am entring the MO receipt entry again there is no ...

XmlSerializer and inherited objects
Hi I have a hirachy of classes which are Message(base), then FileMessage and ChatMessage (extended) I want to serialize the objects and when i am deserizaling i dont know if i am getting FileMessage or ChatMessage. So how to get that object and use it I have written following code for serialization public void Send(Message message) { NetworkStream netWorkStream=null; try { XmlSerializer serializer=new XmlSerializer(message.GetType()); netWorkStream=new NetworkStream(_clientSocket); Stream stream=(Stream)netWorkStream; serializer.Serialize(stream,message); } finally { netWorkStrea...

Collecting form data offline
I've created a simple CRM database suing Access 2007 on our companies share drive. We have a small office with only 5 people using the database. Is it possible to collect from data off line while visiting a client and sync to the database when I'm back in the office? ...

Unrecognised database format '<filename>' in Class Wizard
trying to create my RecordSet classes (derrived from CDaoRecordSet) in class wizard, after selecting my (Acces 2000) database and hitting OK i get this error: Unrecognised database format '<c:\Program Files\Microsoft Visual Studio\My Projects\GMF PoS\POSData.mdb' if i convert the database to Access 97 format (in access) it works, but the release EXE will only access the database on machines with Visual studio installed. I am using Visual C++ 6.0 sorry, misspelling. should be "ClassWizard Error: Unrecognized database format '<filename>'" "Jose...

WSE 2.0- Generating abstract SoapService classes from WSDL
WseWsdl2.exe can be used to generate SoapClient classes from the WSDL. How can we generate abstract classes for WSE 2.0 based web service implementation based on the contracts specified in a WSDL file (just like WSDL.exe). Manually coding the server is not an option as the WSDL file is complex. there is a group for WSE., microsoft.public.dotnet.framework.webservices.enhancements -D "raj712k" <raj712k@discussions.microsoft.com> wrote in message news:8B2A38FC-B82A-4604-98F3-AC736E92F8A5@microsoft.com... > WseWsdl2.exe can be used to generate SoapClient classes from the WS...

Missing Clip Art options Web & Shared Collections are not showing
In Office 2007, when going to Insert>Clip Art the only options available to Search in are My Collections and Office Collections Both Web Collections and Shared Collections are missing. Can anyone provide assistance with this? Thanks, Mike Have you tried a repair? The Organizer has its own Detect and Repair. You might have to create a new catalog file. Find Mstore10.mgc; change it to Mstore10.old. A new catalog will be created the next time you open the Organizer. The Mstore10.mgc is in a folder similar to this (hidden) C:\Users\<<user name>>\AppData\Roaming\...

XMLSerializer Serialize
Iam trying to create a xml file by serializing a custom business object. Iam using a xmltextwriter, but the problem there are invalid characters at the end of the generated file anyone knows a way around it ? tia Dim myStream As New IO.MemoryStream Dim myXMLWriter As New System.Xml.XmlTextWriter(myStream, System.Text.Encoding.UTF8) myXMLWriter.Formatting = System.Xml.Formatting.Indented Dim myShipments As OrderShipments myShipments = CType(myOrder.OrderAddresses(0), COrderAddress).Shipments myShipments.ToXML(myXMLWriter) ...

Does anybody have a CD collection template
I have many CD's and program CD's, but I can never easily find in what rack and in what place in the rack the CD is located at. Is there a template that I can use, to show location, title, version etc?. I'm sure I can make regular columns with that kind of a heading, but maybe there is a nice looking template available that some one would share with me...........Opa Maybe you can adapt one of these http://office.microsoft.com/en-us/results.aspx?Query=inventory&Scope=TC&QueryID=mMV6o9dDy&TRC=35&iStartAt=1 or, try a google search. tj "PeterM" wrote...

POP3 will not collect email (sometimes)
I have a strange problem with MS SBS running Exchange 2003. I have three servers for three different companies all experiencing the same problem. (all running pop3). (in case your wondering the local ISP charge $45 per month for a DSL static IP, STOP laughing, its just how it is when there is a monopoly) Anyway, back to the story. ALL 3 sites fail to collect mail once out of every three or four tries. Even though DNS resolves the pop3 server happily I changed the pop3 server, within exchange, to the IP of the ISP (don't have to resolve DNS no more). This now works every time....

XmlSerializer help
Hi, I have a class: public class Note { public string name; public string information; } And i Serialize this class, but want to Serialize it to an XmlDocument which will contain many of these elements. How do i do this? Thank you, Tim. Timothy, take a look at Chris Lovett's XmlNodeWriter on www.gotdotnet.com [0]. Simply pass the node where you want to insert the serialized XML into the XmlDocument to an XmlNodeWriter and pass the XmlNodeWriter to the Serialize method. -- HTH Christoph Schittko [MVP] Software Architect, .NET Mentor [0] http://gotdotnet.com/Communit...

collection letter #2
I am trying to create collection letters to include all A/R detail. I have managed to include the invoice detail but this does not show any payments, returns or credit memos. Is there a way to include these? We have been using a modified trial balance as a statement to show all activity and have it aged in buckets. This requires an additional cover sheet since there is no easy way to have this report formatted to align in a window envelope. This is a time consuming task. I do not like the statements that are generated using the sales routines since that includes every transaction ...

Problems with XmlSerializer and namespaces
I have an object, Teacher, that has a namespace. Let's call it http://foo. Teacher has a child object called Name, composed of String first, middle, last, etc. Problem I have is when I try to deserialize it. When I deserialize a single Teacher, it works when I put the namespace on the Teacher element. However, if I have just the namespace on Teacher, it will deserialize fine as Teacher. *However*, if I try to deserialize an ArrayOfTeacher, Teacher.Name doesn't deserialize (it's null); without the array, it's OK. What I wound up doing was serializing both a Teacher ...

Filtering out a specific message class for designated users
Hello guys, Here is the situation: I have some exchange 2003 users with a mailbox on which I'd like to filter out specific messages for certain users when I decide I (the admin) want to do this. Do you know of the best way to target a user, specify the message class I want to remove from their stores, all of this logged in as an admin (what additional permissions are required at the store level?) I looked at exmerge but it doesn't look like we can do this. It looks like we may be able to do this via Exchange 2003 recipient policies but not too sure. Thank you, Breiza ...

How Collect Some Start Menu Items into a Group?
I have several menu items related to audio, and I'd like to group them under a single topic. How do I create some entry to move them to? Just create a new folder, then put the shortcuts into it. The Start Menu folders are found here: C:\Documents and Settings\All Users\Start Menu\Programs C:\Documents and Settings\{username}\Start Menu\Programs ju.c "W. eWatson" <wolftracks@invalid.com> wrote in message news:hf05nq$gub$1@news.eternal-september.org... > I have several menu items related to audio, and I'd like to group them > under a single t...

Static class member error
Hello, I'm (trying to) implementing an intenet helper static class for GET and POST calls: CString result = CHttpClient::Get("www.servername.com") The problem is I'm using wininet and when I call CInternetSession::GetHttpConnection(szServerUrl), the compiler gives me the error C2352: 'CInternetSession::GetHttpConnection' : illegal call of non-static member How can I achieve the same result (that is call CHttpClient::Get() statically) using wininet, bypassing this error As an additional info, the member declaration in the .h file is static CString Get(LPCTSTR...

Detail Tax Collected and Tax Analysis report totals should match
The 'Detail Tax Collected' and 'Tax Analysis' report totals do not match. We know the reasoning is that the 'Tax Analysis' report rounds the totals, which causes the two reports to be off by just a few cents to sometimes a few dollars. ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this suggestion, click the "I Agree" button in the message pane. If you do not see the button, follow this link to open the suggestion in the Microsoft Web-based Newsreader and then click &...