简体   繁体   中英

Convert true and false to 1 and 0 in XmlElement in C#

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM