views:

324

answers:

3

Having the following class (.Net 3.5):

public class Something
{
    public string Text {get; private set;}

    private Something()
    {
        Text = string.Empty;
    }

    public Something(string text)
    {
        Text = text;
    }
}

This serializes without error but the resulting XML does not include the Text property since it does not have a public setter.

Is there a way (the simpler, the better) to have the XmlSerializer include those properties?

A: 

No. XML Serialization will only serialized public read/write fields and properties of objects.

Arnshea
A: 
Partha Choudhury
XmlSerializer doesn't need [Serializable], and it doesn't do anything at all towards letting you serialize read-only members.
Marc Gravell
It needs [Serializable] sometimes.
Henk Holterman
@Henk: when does it need [Serializable]?
John Saunders
IIRC, the WSDL generator for asmx needs it... but not XmlSerializer itself...
Marc Gravell
No, sorry, I thought this was about the SOAPFormatter.
Henk Holterman
+3  A: 

XmlSerializer only cares about public read/write members. One option is to implement IXmlSerializable, but that is a lot of work. A more practical option (if available and suitable) may be to use DataContractSerializer:

[DataContract]
public class Something
{
    [DataMember]
    public string Text {get; private set;}

    private Something()
    {
        Text = string.Empty;
    }

    public Something(string text)
    {
        Text = text;
    }
}

This works on both public and private members, but the xml produced is not quite the same, and you can't specify xml attributes.

Marc Gravell
Thanks Marc,That could work, I didn't know about this attribute. The two drawbacks you mentioned are they the only ones or are there other gotchas as well?
Stecy
In many ways, it is a /better/ serializer (you'd hope so since it is newer) - but it has different aims. It isn't as flexible if you need tight control of the xml. But if you just want you data to serialize, then it should work. Or try protobuf-net ;-p
Marc Gravell
Note you need to add a reference to System.Runtime.Serialization (from .NET 3.0)
Marc Gravell