简体   繁体   English

在C#中的XmlElement中将true和false转换为1和0

[英]Convert true and false to 1 and 0 in XmlElement in C#

I am working with a SOAP web service from a third party. 我正在使用第三方的SOAP Web服务。 I have generated objects using the XSD.exe tool. 我已经使用XSD.exe工具生成了对象。 The problem is that I need to send an XmlElement that I'm serialising. 问题是我需要发送要序列化的XmlElement Their service is throwing an error because it expects all boolean values to be represented by 1 and 0 instead of true and false. 他们的服务抛出错误,因为它期望所有boolean值都由1和0表示,而不是true和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. 我知道我可以使用这样的自定义序列化程序: IXmlSerializable Interface或这样: 使XmlSerializer输出简单类型的替代值,但是它们涉及我更改Xsd.exe工具生成的代码,并且每次都很难维护升级。

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. 您可以使对象忽略bool值,而是使用其他变量来显示它。 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. 这将使XML解析器忽略real属性,而使用格式化函数。

You could remove the setter if you do not need to parse it. 如果不需要解析它,则可以删除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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