Xml Serialising Exposes a Class Too Much

A

aine_canby

Hi,

The code below is something I found on the net which serializes lists
of objects. I have a few problems with it though. First, I hate that
you have to have a default constructor - public Item() {}. For
example, if you have a Directory class I think it doesn't make sense
to have a default constructor. Instead, you wan't to pass it a string
etc. Whats a directory without a name? My point is that I think there
are situations where a class should not have a default constructor,
but if your serializing it your forced to anyway.

Also, in the example below, name and price are public. But if you make
them private then you are forced to define a get and set accessor for
each, otherwise xml serialization will get upset. This defeats the
whole point in having private with respect to the fact that users can
now set the name or value whenever they feel like it, rather than at
construction. So again with our Directory example, I'd prefer to have
no set on the Directory name since I think that this should only be
set when you create the object.

Direcory whatsMyPurpose = new Directory();
whatsMyPurpose.Name = ("c:/now_i_know");
whatsMyPurpose.Name = ("c:/or_do_i");

What do you think?

/Aine



using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

// Shopping list class which will be serialized
[XmlRoot("shoppingList")]
public class ShoppingList {
private ArrayList listShopping;

public ShoppingList() {
listShopping = new ArrayList();
}

[XmlElement("item")]
public Item[] Items {
get {
Item[] items = new Item[ listShopping.Count ];
listShopping.CopyTo( items );
return items;
}
set {
if( value == null ) return;
Item[] items = (Item[])value;
listShopping.Clear();
foreach( Item item in items )
listShopping.Add( item );
}
}

public int AddItem( Item item ) {
return listShopping.Add( item );
}
}

// Items in the shopping list
public class Item {
[XmlAttribute("name")] public string name;
[XmlAttribute("price")] public double price;

public Item() {
}

public Item( string Name, string Price ) {
name = Name;
price = Price;
}
}
 
M

Marc Gravell

If you use DataContractSerializer, you can mark private members
(including fields) as DataMember (not just public properties), however
I believe that you still need a default ctor. One other option is to
implement IXmlSerializable, but this largely defeats the purpose of an
automatic serializer...

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top