Anemoia
Anemoia

Reputation: 8116

Read XML with C# with custom deserializer

I'm trying to deserialize a piece of XML offered by some API. However this API is dumb, for example, a bool is not true, but True. And having an element

[XmlElement("Foo")]
public bool Foo { get;set; }

and then the matching XML:

<...><Foo>True</Foo></...>

does NOT work, because True is not a valid representation of bool (the API is written in Python, which is, I think, more forgiving).

Is there any way to put some attribute on my property Foo to say to the system: when you encounter this element, put it through this converter class?

Edit: The XML is large, and most of them are stupid, not directly convertible objects, like 234KB, which I need to parse to the exact value.

Do I need to write a wrapper property for each of them?

Upvotes: 0

Views: 633

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039180

You could use a backing property:

public class MyModel
{
    [XmlIgnore]
    public bool Foo 
    {
        get
        {
            return string.Equals(FooXml, "true", StringComparison.OrdinalIgnoreCase);
        }
        set
        {
            FooXml = value.ToString();
        }
    }

    [XmlElement("Foo")]
    public string FooXml { get; set; }
}

Upvotes: 1

Related Questions