views:

324

answers:

2

I am working on some classes which I need to serialize/deserialize to xml, that can be used for configuration. Here is a sample of what I am trying to do

[Serializable]
public class MyConfig
{
    [XmlElement] 
    public string ConfigOption { get; set; }
    [XmlElement] 
    public Uri SomeUri { get; set; }
}

I want to override the way that the Uri property is being serialized. So when the serialize method is called, I want it to look like this

<MyConfig>
  <ConfigOption></ConfigOption>
  <SomeUri uri="" />
</MyConfig>

Is there a way to plug into .net serialization and override how all Uri objects are serialized and deserialized? Note that I dont want to create a class called MyUri and use that as the type of SomeUri, I just want to plug into the place where the serialized serializes types of Uri and override that behavior.

+2  A: 
public class MyConfig
{
    [XmlElement] 
    public string ConfigOption { get; set; }
    [XmlElement] 
    public MyUri SomeUri { get; set; }
}

public class MyUri
{
    [XmlAttribute(Name="uri")]
    public Uri SomeUri { get; set; }
}
John Saunders
yeah, this will work, but I dont want to create another class to wrap any object that I need to serialize/deserialize differently. I want to plug into the place where this property is being serialized and have control of how it should look like.
Vadim Rybak
There is no such place. The only choice is to completely take over serialization.
John Saunders
Also if you are using XmlSerializer with that code it will not work anyways since Uri doesn't have a default constructor it can't be serialized with XmlSerializer, if you want to have a Uri object be serialized you have to implement IXmlSerializable and then take over where needed. It would be easier to store it as a string in the public serializable property if you want to use XmlSerializer.
Rodney Foley
+1  A: 

Since you don't want to create a new wrapper class for Uri, I think your only alternative is to MyConfig implement IXmlSerializable in order to have complete control over the XML serialization process.

However if you do this you'll have an all or nothing approach, since you will need to completely implement serialization and not only for the Uriproperty.

João Angelo