title: Need help validating XML against XSD in C#
body: <p>I'm writing a WPF application that requires XML files to be validated. I have the following class to validate XML against one or more XSD files:</p>
  
  <pre><code>public class XSDValidator
  {
      public List&lt;XmlSchema&gt; Schemas { get; set; }
      public List&lt;String&gt; Errors { get; set; }
      public List&lt;String&gt; Warnings { get; set; }
  
      public XSDValidator()
      {
          Schemas = new List&lt;XmlSchema&gt;();
      }
  
      /// &lt;summary&gt;
      /// Add a schema to be used during the validation of the XML document
      /// &lt;/summary&gt;
      /// &lt;param name="schemaFileLocation"&gt;The file path for the XSD schema file to be added for validation&lt;/param&gt;
      /// &lt;returns&gt;True if the schema file was successfully loaded, else false (if false, view Errors/Warnings for reason why)&lt;/returns&gt;
      public bool AddSchema(string schemaFileLocation)
      {
          // Reset the Error/Warning collections
          Errors = new List&lt;string&gt;();
          Warnings = new List&lt;string&gt;();
  
          XmlSchema schema;
  
          if (!File.Exists(schemaFileLocation))
          {
              throw new FileNotFoundException("The specified XML file does not exist", schemaFileLocation);
          }
  
          using (var fs = new FileStream(schemaFileLocation, FileMode.Open))
          {
              schema = XmlSchema.Read(fs, ValidationEventHandler);
          }
  
          var isValid = !Errors.Any() &amp;&amp; !Warnings.Any();
  
          if (isValid)
          {
              Schemas.Add(schema);
          }
  
          return isValid;
      }
  
      /// &lt;summary&gt;
      /// Perform the XSD validation against the specified XML document
      /// &lt;/summary&gt;
      /// &lt;param name="xmlLocation"&gt;The full file path of the file to be validated&lt;/param&gt;
      /// &lt;returns&gt;True if the XML file conforms to the schemas, else false&lt;/returns&gt;
      public bool IsValid(string xmlLocation)
      {
          if (!File.Exists(xmlLocation))
          {
              throw new FileNotFoundException("The specified XML file does not exist", xmlLocation);
          }
  
          using (var xmlStream = new FileStream(xmlLocation, FileMode.Open))
          {
              return IsValid(xmlStream);
          }
      }
  
      /// &lt;summary&gt;
      /// Perform the XSD validation against the supplied XML stream
      /// &lt;/summary&gt;
      /// &lt;param name="xmlStream"&gt;The XML stream to be validated&lt;/param&gt;
      /// &lt;returns&gt;True is the XML stream conforms to the schemas, else false&lt;/returns&gt;
      private bool IsValid(Stream xmlStream)
      {
          // Reset the Error/Warning collections
          Errors = new List&lt;string&gt;();
          Warnings = new List&lt;string&gt;();
  
          var settings = new XmlReaderSettings
          {
              ValidationType = ValidationType.Schema
          };
          settings.ValidationEventHandler += ValidationEventHandler;
  
          foreach (var xmlSchema in Schemas)
          {
              settings.Schemas.Add(xmlSchema);
          }
  
          var xmlFile = XmlReader.Create(xmlStream, settings);
  
          while (xmlFile.Read()) { }
  
          return !Errors.Any() &amp;&amp; !Warnings.Any();
      }
  
      private void ValidationEventHandler(object sender, ValidationEventArgs e)
      {
          switch (e.Severity)
          {
              case XmlSeverityType.Error:
                  Errors.Add(e.Message);
                  break;
              case XmlSeverityType.Warning:
                  Warnings.Add(e.Message);
                  break;
          }
      }
  }
  </code></pre>
  
  <p>The above code is open-source and can be found <a href="http://satalketo.com/2013/09/validating-xml-against-xsd/" rel="nofollow">here</a>. Now, it is called like so:</p>
  
  <pre><code>var validator = new XSDValidator();
  validator.AddSchema(@"C:\code\xml\books.xsd");
  
  foreach (CheckableListItem file in FileFullPathChecklist)
  {
      if (file.IsChecked)
      {
          if (validator.IsValid(file.Filename)) 
          {
              ValidatedXMLFiles++;
          }
      }
  }
  </code></pre>
  
  <p>In my testing of the XSD validation, I'm using 4 XML files: one of them, <code>books.xml</code>, corresponds to the hard-coded schema <code>books.xsd</code>. The other three are random XML files I pulled from other sources, and I have verified that they are not valid against <code>books.xsd</code>. However, upon running the code, <code>ValidatedXMLFiles</code> shows a value of 4 instead of 1.</p>
  
  <p>I've verified as much as I can think of from the <code>XSDValidator</code> class; I tried manually adding a random string to <code>Errors</code>, and <code>IsValid</code> returned false in that case. One thing that I thought was interesting was, when I tried changing the schema file name to something that doesn't exist, a <code>TargetInvocationException</code> was thrown instead of the <code>FileNotFoundException</code> that I expected. I don't know if that means anything, but that's the only strange behavior I've seen. Can anyone provide any assistance?</p>