0

I am working with a SOAP web service from a third party. I have generated objects using the XSD.exe tool. The problem is that I need to send an XmlElement that I'm serialising. Their service is throwing an error because it expects all boolean values to be represented by 1 and 0 instead of true and false.

I know I can use a custom serializers such as this: IXmlSerializable Interface or this: Making the XmlSerializer output alternate values for simple types but they involve me changing the code generated by the Xsd.exe tool and would be difficult to maintain every time there was an upgrade.

Am I missing something or is there a another way to achieve what I'm looking for?

dbc
  • 104,963
  • 20
  • 228
  • 340
davy
  • 4,474
  • 10
  • 48
  • 71
  • Can't you skip serializing the `bool` property, and define a computed public `int` property returning `BoolProp ? 1 : 0` instead? – Sergey Kalinichenko Aug 29 '16 at 09:15
  • Please attach sample code? – Lalit Rajput Aug 29 '16 at 09:15
  • The service has hundreds of complex types and many contain bools so I'm looking for something that I don't need to do on a property by property basis. – davy Aug 29 '16 at 09:24
  • 1
    Using an approach as @dasblinkenlight suggested together with [Fody](https://github.com/Fody/Fody) could get you the desired result. I don't think there is an addin which does such a transformation so you would have to create one yourself. The benefit of such a solution would be that the special handling of `bool` values would be transparent for the rest of your application. – fknx Aug 29 '16 at 09:37
  • I don't think so. Identical questions were never answered [here](https://stackoverflow.com/questions/36722407) or [here](https://stackoverflow.com/questions/38763679). Even if you subclass `XmlWriter` and override `WriteValue(bool value)` it doesn't help, since `XmlSerializer` calls `WriteRaw(string value)` with the strings `"true"` or `"false"` directly instead. Could you serialize to an intermediate `XDocument` and postprocess it? – dbc Aug 29 '16 at 09:40

1 Answers1

0

You could make your object ignore the bool value but instead use a different Variable to show it. As example:

    [IgnoreDataMember, XmlIgnore]
    public bool BoolProp  { get; set; }

    /// <summary>
    ///     XML serialized BoolProp 
    /// </summary>
    [DataMember(Name = "BoolProp"]
    [XmlElement(ElementName = "BoolProp"]
    public int FormattedBoolProp 
    {
        get { 
            return BoolProp ? 1 : 0;
        }
        set { BoolProp = value==1 }
    }

This will make the XML parser ignore the real property, but instead use the formatted function.

You could remove the setter if you do not need to parse it.

Flying Dutch Boy
  • 344
  • 3
  • 17