问题
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:
[XmlAttributeAttribute]
[DefaultValueAttribute(Version.Version_1_1)]
public Version Version { get; set; }
[Serialization.XmlIgnoreAttribute]
public bool VersionSpecified { get; set; }
And this is the enumeration on which it is based:
/// <remarks/>
[GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[Serializable]
public enum Version
{
[XmlEnumAttribute("1.0")]
Version_1_0,
[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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/3411542/xml-serialization-of-the-default-values-of-optional-attributes