Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize XML element presence to bool in C#

I'm trying to deserialize some XML from a web service into C# POCOs. I've got this working for most of the properties I need, however, I need to set a bool property based on whether an element is present or not, but can't seem to see how to do this?

An example XML snippet:

<someThing test="true">
    <someThingElse>1</someThingElse>
    <target/>
</someThing>

An example C# class:

[Serializable, XmlRoot("someThing")]
public class Something
{
    [XmlAttribute("test")]
    public bool Test { get; set; }

    [XmlElement("someThingElse")]
    public int Else { get; set; }

    /// <summary>
    /// <c>true</c> if target element is present,
    /// otherwise, <c>false</c>.
    /// </summary>   
    [XmlElement("target")]
    public bool Target { get; set; }
}

This is a very simplified example of the actual XML and object hierarchy I'm processing, but demonstrates what I'm trying to achieve.

All the other questions I've read related to deserializing null/empty elements seem to involve using Nullable<T>, which doesn't do what I need.

Does anyone have any ideas?

like image 853
James Simm Avatar asked May 15 '12 13:05

James Simm


1 Answers

One way to do it would be to use a different property to get the value of the element, then use the Target property to get whether that element exists. Like so.

[XmlElement("target", IsNullable = true)]
public string TempProperty { get; set; }

[XmlIgnore]
public bool Target
{
    get
    {
        return this.TempProperty != null;
    }
}

As even if an empty element exists, the TempProperty will not be null, so Target will return true if <target /> exists

like image 179
Balthy Avatar answered Sep 29 '22 00:09

Balthy