WSDL time format is ignored from Visual Studio

2019-08-08 16:16发布

问题:

A WSDL file from a customer specifies the time data type using this syntax: <xsd:simpleType name="time"><xsd:restriction base="xsd:time"><xsd:pattern value="[0-9]{2}:[0-9]{2}:[0-9]{2}"/></xsd:restriction></xsd:simpleType>

I included the WSDL file as "Web Reference" (not Service Reference) in a Visual Studio C# project. Which generates this code:

[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, DataType="time")]
public System.DateTime I_TIMETO {
get {
     return this.i_TIMETOField;
}
set {
     this.i_TIMETOField = value;
}

}

The problem is that in the generated payload, the pattern from the WSDL file ([0-9]{2}:[0-9]{2}:[0-9]{2}), is completly ignored. I.e. the payload looks like:

<I_TIMETO xmlns="">17:11:00.0000000+01:00</I_TIMETO> 

instead of:

<I_TIMETO xmlns="">17:11:00</I_TIMETO> 

It is not possible to change the Webservice and I don't want to change the auto generated code.

回答1:

I think there is no good solution, so you have to edit the auto generated code.

Create a partial class of the auto generated code and add a string property with the correct formatting in it:

[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, 
 DataType = "string", ElementName = "I_TIMETO")]
public string I_TIMETO_STR
{
    get
    {
        return this.i_TIMETOField.ToString("HH:mm:ss");
    }
    set
    {
        this.i_TIMETOField = DateTime.ParseExact(value, "HH:mm:ss", CultureInfo.InvariantCulture);
    }
}

Now go to the auto generated property and add a XmlIgnore:

[System.Xml.Serialization.XmlIgnore] 
public System.DateTime I_TIMETO{...


回答2:

Here you can find solution which does not involve editing the auto generated code: https://stackoverflow.com/a/43265625/1104587