Monday, June 18, 2012

Prefer XmlSerializer When Using svcutil To Generate Client Code From WSDL

I have a WSDL from a web service server which includes the following in its types:

<xs:element minOccurs="0" name="countryID" type="xs:int"/>

This is supposed to represent an optional int element named countryID.  When I run svcutil.exe (from C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin) against it, I get the following generated code:
        [System.Runtime.Serialization.DataMemberAttribute()]
public int countryID
{
    get
    {
        return this.countryIDField;
    }
    set
    {
        this.countryIDField = value;
    }
}

The "IsRequired=true" property is not set on the DataMemberAttribute.  But there's no way to indicate that I want a given instance to be absent!  Some googling revealed that I could modify the generated code (which I hate doing) to use "DataMemberAttribute(EmitDefaultValue=false)" (see http://msdn.microsoft.com/en-us/library/aa347792.aspx?ppud=4).  But if I do this, I cannot use a countryID value of zero, as this will be interpreted as the default value, and no countryID element will be generated!

The solution: add the "/serializer:XmlSerializer" command line option, which causes the following to be generated:


    [System.Xml.Serialization.XmlElementAttribute(Order=0)]
    public int countryID
    {
        get
        {
            return this.countryIDField;
        }
        set
        {
            this.countryIDField = value;
        }
    }
   
    ///
    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public bool countryIDSpecified
    {
        get
        {
            return this.countryIDFieldSpecified;
        }
        set
        {
            this.countryIDFieldSpecified = value;
        }
    }


With this construct, as I described in my earlier post about optional attributes, setting countryIDFieldSpecified to "false" will not emit the countryID element.

No comments:

Post a Comment