views:

36

answers:

3

Let's suppose I have xml like this one:

<Server Active="No">
    <Url>http://some.url&lt;/Url&gt;
</Server>

C# class looks like this:

public class Server
{
   [XmlAttribute()]
   public string Active { get; set; }

   public string Url { get; set; }
}

Is it possible to change Active property to type bool and have XmlSerializer coerce "Yes" "No" to bool values?

Edit: Xml is received, I cannot change it. So, in fact, i'm interested in deserialization only.

+2  A: 

Yes, you can implement IXmlSerializable and you will have control over how the xml is serialized and deserialized

Matt Dearing
However, in the general case (if we assume there are nested objects etc) that is a pretty horrible interface to have to implement.
Marc Gravell
A: 
public class Server
{
   [XmlAttribute()]
   public bool Active { get; set; }

   public string Url { get; set; }
}

The previous class should end up in that serialized form :

<Server Active="false">
    <Url>http://some.url&lt;/Url&gt;
</Server>
Seb
...which doesn't really match what the OP asked for (he can't change the xml)?
Marc Gravell
+1  A: 

I might look at a second property:

[XmlIgnore]
public bool Active { get; set; }

[XmlAttribute("Active"), Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public string ActiveString {
    get { return Active ? "Yes" : "No"; }
    set {
        switch(value) {
            case "Yes": Active = true; break;
            case "No": Active = false; break;
            default: throw new ArgumentOutOfRangeException();
        }
    }
}
Marc Gravell
This is pretty neat way to do it. My only complaint is that ActiveString will be visible in IntelliSense within same project.
Kugel
@Kugel - within the *same* project, yes. The `[EditorBrowsable(...)]` at least tries to deal with *other* projects, though.
Marc Gravell