title: Validating large Xml files
body: <p>As a follow up to my issue <a href="https://stackoverflow.com/questions/2884795/transforming-large-xml-files">transforming large Xml files</a>, I now need to validate the schema.</p>
  
  <p>I was using this extension method, which can clearly be improved upon as it's not working correctly either</p>
  
  <pre><code>public static XElement ValidateXsd(this XElement source, string xsdPath)
  {
      var errors = new XElement("Errors");
  
      // Reference: http://msdn.microsoft.com/en-us/library/bb358456.aspx
      var xsd = XDocument.Load(xsdPath);
      var xml = XDocument.Load(source.CreateReader());
  
      var schemas = new XmlSchemaSet();
      schemas.Add("", xsd.CreateReader());
  
      if (xml.Document != null)
      {
          xml.Document.Validate(schemas,
              // Validation Event/Error Handling
              (sender, e) =&gt;
                  {
                      var message = e.Message
                          .Replace(
                              "element is invalid - The value '' is invalid according to its datatype 'requiredString' - The actual length is less than the MinLength value.",
                              "cannot be blank.")
                          .Replace(
                              "is invalid according to its datatype 'size' - The Pattern constraint failed.",
                              "must be numeric.")
                          .Replace(
                              "element is invalid",
                              "is invalid.");
  
                      errors.Add(new XElement("Error", message));
                  }
              );
      }
  
      // If there were errors return them, otherwise return null
      return errors.Elements().Count() &gt; 0 ? errors : null;
  }
  </code></pre>