title: Validating Serialized Xml Prior To Saving To A File
body: <p>I have an Xml schema, CustomerData.xsd, that I use Microsoft's xsd.exe to create the class CustomerData. </p>
  
  <p>My program reads in an Xml file uses XmlSerializer to get an instance of CustomerData using the following code:</p>
  
  <pre><code>XmlSerializer serializer = new XmlSerializer(typeof(CustomerData));
  TextReader textReader = new StreamReader(fileName);
  CustomerData customerData = (CustomerData)serializer.Deserialize(textReader);
  textReader.Close();
  </code></pre>
  
  <p>While my program runs customerData can be modified and there is a possibility that some of the values might not be valid according to the schema.</p>
  
  <p>Before the user saves this data back to a file I want to be able to validate it. How can I validate the data before saving?</p>
  
  <p>Note - I compile the schema as an Embedded Resource so I can use code such as the following to get to the schema:</p>
  
  <pre><code>Assembly myAssembly = typeof(CustomerData).Assembly;
  Stream schemaStream = myAssembly.GetManifestResourceStream(schemaResourceName);
  </code></pre>
  
  <p>I also know how to make a validating SchemaReader:</p>
  
  <pre><code>XmlReader schemaReader = XmlReader.Create(schemaStream);
  XmlReaderSettings settings = new XmlReaderSettings();
  settings.Schemas.Add(null, schemaReader);
  settings.ValidationType = ValidationType.Schema;
  </code></pre>
  
  <p>I just don't know what do do next.</p>