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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With