Vb.net 来自web服务的类型不明数据的属性中的异常处理

Vb.net 来自web服务的类型不明数据的属性中的异常处理,vb.net,web-services,exception-handling,Vb.net,Web Services,Exception Handling,我需要使用Web服务中的数据。我接收xml数据并使用它通过属性设置器创建对象 在一种特定情况下,对象的属性(称为“is_active”并指示该对象在应用程序中是活动的还是非活动的)有时表示为 <field type="BooleanField" name="is_active">1</field> 1 在其他时候 <field type="BooleanField" name="is_active">True</field> True 客户

我需要使用Web服务中的数据。我接收xml数据并使用它通过属性设置器创建对象

在一种特定情况下,对象的属性(称为“is_active”并指示该对象在应用程序中是活动的还是非活动的)有时表示为

<field type="BooleanField" name="is_active">1</field>
1
在其他时候

<field type="BooleanField" name="is_active">True</field>
True
客户机代码要求我使用整数1和0表示。返回的字符串“True”或“False”会导致System.FormatException,这与预期的一样

处理这种情况最优雅的方式是什么


谢谢。

您使用什么来处理数据?因为这显然是自定义序列化,所以似乎您应该能够调整“BooleanField”处理来处理这两个

不过,在我看来,您并没有按照预期的方式使用xml。。。将其指定为元素/属性会更容易,就像
XmlSerializer
那样(实际上-为什么不直接使用
XmlSerializer
?):


您使用什么来处理数据?因为这显然是自定义序列化,所以似乎您应该能够调整“BooleanField”处理来处理这两个

不过,在我看来,您并没有按照预期的方式使用xml。。。将其指定为元素/属性会更容易,就像
XmlSerializer
那样(实际上-为什么不直接使用
XmlSerializer
?):


我无法控制正在接收的xml。因此,基本上我得到的是不一致的xml。现在,我想我将只在xml中查找True,并将其替换为1。我无法控制正在接收的xml。因此,基本上我得到的是不一致的xml。现在,我想我将在xml中查找True,并用1替换它。
<isActive>true</isActive>
<foo ... isActive="true" ... />
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);
    }
}