title: How to find invalid XML node in XDocument that is validated against a schema (XmlSchemaValidationException.SourceObject is null)
body: <p>I have an <code>XDocument</code> that I validate against an XML schema. When the <code>XDocument</code> is invalid I need to find the invalid XML nodes so that the user can easily navigate to the respective place in my application (e.g. by double-clicking a message on a message grid).</p>
  
  <p>I use the <code>System.Xml.Schema.Validate()</code> extension method for that purpose. The second argument of the Validate() method is a <code>System.Xml.ValidationEventHandler</code> which is called on every invalid XML element. It passes a <code>System.Xml.ValidationEventArgs</code>. The <code>ValidationEventArgs.Exception</code> can be casted to <code>System.Xml.Schema.XmlSchemaValidationException</code>. Now the
  <code>XmlSchemaValidationException</code> has a property <code>SourceObject</code> which I expected to hold a reference to the invalid XML node. Unfortunately it is always null.</p>
  
  <p>The following snippet illustrates my usage:</p>
  
  <pre><code>XDocument doc = XDocument.Load(@"c:\temp\booksSchema.xml");
  
  // Create the XmlSchemaSet class.
  XmlSchemaSet sc = new XmlSchemaSet();
  
  // Add the schema to the collection.
  sc.Add("urn:bookstore-schema", @"c:\temp\books.xsd");
  
  // Validate against schema
  doc.Validate(sc, delegate(object sender, ValidationEventArgs e)
                  {
                      XmlSchemaValidationException ve = e.Exception as XmlSchemaValidationException;
                      if (ve != null)
                      {
                          object errorNode = ve.SourceObject;    
                          // ve.SourceObject is always null
                      }
                  });
  </code></pre>
  
  <p>The validation itself works correctly, but I cannot get a reference on the invalid node. Strangely, the same approach works well for <code>System.Xml.XmlDocument</code>, but unfortunately I must work with <code>XDocument</code> in this context.</p>
  
  <p>Does anyone have a suggestion how the invalid node can be found in <code>XDocument</code>?</p>