title: .Net XML Serialization based on an XSD?
body: <p>I've been serialising and deserialising .net objects using the XmlSerializer class without problem, however we now need somebody else to look at that data to perform some analysis on it.</p>
  
  <p>In order to help with that we've produced an XSD based on our class like so:
  xsd.exe /t:DataClass Assembly.exe</p>
  
  <p>The start of the XSD looks like this:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt;
    &lt;xs:element name="DataClass" nillable="true" type="DataClass" /&gt;
    &lt;xs:complexType name="DataClass"&gt;
      &lt;xs:complexContent mixed="false"&gt;
        &lt;xs:extension base="BaseDataClass"&gt;
          &lt;xs:sequence&gt;
            &lt;xs:element minOccurs="0" maxOccurs="1" name="StudyID" type="xs:string" /&gt;
            &lt;xs:element minOccurs="1" maxOccurs="1" name="Position" type="xs:int" /&gt;
            &lt;xs:element minOccurs="1" maxOccurs="1" name="IViewer" type="xs:string" /&gt;
  </code></pre>
  
  <p>The XML is produced like this (where obj is an instance of our DataClass):</p>
  
  <pre><code>Dim xs As New XmlSerializer(obj.GetType)
  Dim xmlTextWriter As New XmlTextWriter(memoryStream, Encoding.UTF8)
  xs.Serialize(xmlTextWriter, obj)
  </code></pre>
  
  <p>...which produces XML looking like this:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;DataClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
      &lt;Version&gt;SixMonthQ-E1&lt;/Version&gt;
      &lt;IViewer xsi:nil="true" /&gt;
      &lt;Language xsi:nil="true" /&gt;
      ...
      &lt;StudyID&gt;12345&lt;/StudyID&gt;
  </code></pre>
  
  <p>Bizarly, the XML produced does not adhere to the XSD generated from the same class.  </p>
  
  <p>My question then is, is there a way of telling the XmlSerializer to serialize the object based on a given XSD?  </p>
  
  <p>As an aside, I've looked at other ways of fixing this:
  I've tried re-generating the classes from the generated XSD - this seemed to have the same problem.
  I could explicitly state an ordering of elements using the XmlElement attribute, but I don't fancy doing that for 400+ public properties.</p>