i have generated a cs-classes with the xsd-tool from some xml scheme.
The scheme is a very complex scheme generated from uml-class descriptions.
Now I have written a simple test to ensure the functionality of the generated xsd-classes.
The test uses XmlSerializer to create the xml-file.
In my XSD-scheme there are some obligatory elements (definition with minocc=1 and maxocc=1 by xsd-default).
For example (simplified):
<xs:element name="order">
<xs:complexType>
...
<xs:element name="orderId" type="string"/>
<xs:element name="material" type="Material"/>
...
<xs:complexType>
Material is a complex type, which consists of several elements. It is part of order.
These elements should always exists in the resulting xml-file, even if they are empty or contains only empty elements. Now, if I serialize a class instance to an xml-file, only the elements appear where the class-propertys contain a value. If I set orderId the orderId-element appears, but not the material-element because in my class instance it’s null. As a result my xml-file is not valid to the xsd-schema.
Do you have an idea how i can validate the resulting xml-file with my xsd file during serialization? Is there a way to tell XmlSerializer that it should always generate obligatory elements (perhaps with a default value)?
Or is there a way to validate the structure of the class instance that should be serialized?
You cannot generate automatically elements to fulfill your required rules.
On your second question you can validate the generated xml with XmlReader and XmlSchema objects.
A small example would look like this:
This example takes a TextReader (can be a StreamReader, StringReader etc. ) and an XmlSchema object (you can construct one from the xsd file or whatever – check the documentation for it) and returns a list of validation errors.