views:

159

answers:

1

Hi,

I need to consume data from a webservice. I am receiving xml data and using this to create objects through property setters.

In one particular case, an attribute of the object (called "is_active" and indicates whether the object is active or inactive in the application) is represented sometimes by

<field type="BooleanField" name="is_active">1</field>

and at other times by

<field type="BooleanField" name="is_active">True</field>

The client code requires me to represent this using integers 1 and 0. The returned string "True" or "False" results in System.FormatException, as expected.

What is the most graceful way to deal with this situation?

Thanks.

+1  A: 

What are you using to process the data? Since that is obviously custom serialization, it seems like you should be able to tweak "BooleanField" processing to handle both...

IMO, though, your not using xml the way it is intended... it would be easier to specify this as elements/attributes, like how XmlSerializer would (indeed - why not just use XmlSerializer?):

<isActive>true</isActive>

or

<foo ... isActive="true" ... />

Note that the xml standard for true/false is lower case...


Additionally; if you are using TypeConverter - you can just change the converter:

using System;
using System.Collections.Generic;
using System.ComponentModel;
public class Program
{
    static void Main()
    {
        TypeDescriptor.AddAttributes(typeof(bool),
            new TypeConverterAttribute(typeof(MyBooleanConverter)));

        TypeConverter conv = TypeDescriptor.GetConverter(typeof(bool));
        Console.WriteLine((bool)conv.ConvertFrom("True"));
        Console.WriteLine((bool)conv.ConvertFrom("true"));
        Console.WriteLine((bool)conv.ConvertFrom("False"));
        Console.WriteLine((bool)conv.ConvertFrom("false"));
        Console.WriteLine((bool)conv.ConvertFrom("0"));
        Console.WriteLine((bool)conv.ConvertFrom("1"));
    }
}

class MyBooleanConverter : BooleanConverter
{
    static readonly Dictionary<string, bool> map
        = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase)
        { { "true", true }, { "false", false },
          { "1", true }, { "0", false } };

    public override object ConvertFrom(ITypeDescriptorContext context,
        System.Globalization.CultureInfo culture, object value)
    {
        string s = value as string;
        bool result;
        if (!string.IsNullOrEmpty(s) && map.TryGetValue(s, out result))
        {
            return result;
        }
        return base.ConvertFrom(context, culture, value);
    }
}
Marc Gravell
I do not have control over the xml I am receiving. So basically I am being provided xml which happens to be inconsistent. Right now I think I will just look for the True in the xml and replace it with 1.
chefsmart