views:

228

answers:

2

I have a set of classes build using xsd.exe, and I am trying to serialise them. However, an attribute is not being included in the resulting XML. Here is part of the schema where the problem lies.

<xsd:element name="Widget">
    <xsd:complexType>
        /* sequence removed for brevity */
        <xsd:attribute name="Version" type="Version" use="optional" default="1.1"/>
    </xsd:complexType>
</xsd:element>
<xsd:simpleType name="Version">
    <xsd:restriction base="xsd:string">
        <xsd:enumeration value="1.0"/>
        <xsd:enumeration value="1.1"/>
    </xsd:restriction>
</xsd:simpleType>

xsd.exe generated a property called "Version" on a "Widget" class and another property called "VersionSpecified", but this not appear to generate the attribute when I serialize even when set to true:

        /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    [System.ComponentModel.DefaultValueAttribute(Version.Version_1_1)]
    public Version Version
    {
        get
        {
            return this.version;
        }
        set
        {
            this.version = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public bool VersionSpecified
    {
        get
        {
            return this.versionSpecified;
        }
        set
        {
            this.versionSpecified = value;
        }
    }

And this is the enumeration on which it is based:

    /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
public enum Version
{

    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("1.0")]
    Version_1_0,

    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("1.1")]
    Version_1_1,
}

Code snippet as per request

        Widget widget = new Widget();
        widget.Version = Version.Version_1_1;
        widget.VersionSpecified = true;    

        XmlSerializer serializer = new XmlSerializer(widget.GetType());
        serializer.Serialize(/*Memory Stream object*/, widget);

Does anyone have any thoughts on why the serialization refuses to introduce the attribute?

A: 

You have to set the VersionSpecified flag to true before serializing. That's how it knows whether or not this optional attribute is to be serialized.

John Saunders
Hi John, doing exactly that just prior to serializing. There's nothing special I need to do to the serializer itself, is there?
Jason
Please show the code you use for serializing, and no, you shouldn't have to do anything else special.
John Saunders
Added code snippet to bottom as per your request.
Jason
+1  A: 

Its because you specified the default value as "1.1". The serialiser will not create the element/attribute when the property is equal to its default value.

Richard Schneider
Good catch. I missed that.
John Saunders