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?
You can specify the default value of an XML element or XML attribute by applying a DefaultValueAttribute to a member. To examine the result of applying the value, compile the application into a DLL or executable, and pass the resulting file as an argument to the XML Schema Definition tool (XSD.exe).
XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.
XmlRootAttribute Class (System.Xml.Serialization) Controls XML serialization of the attribute target as an XML root element.
XML serialization serializes only the public fields and property values of an object into an XML stream. XML serialization does not include type information. For example, if you have a Book object that exists in the Library namespace, there is no guarantee that it is deserialized into an object of the same type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With