How to find invalid XML node in XDocument that is validated against a schema (XmlSchemaValidationException.SourceObject is null)
-
Thursday, January 24, 2013 8:32 AM
I have an
XDocumentthat I validate against an XML schema. When theXDocumentis 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).I use the
System.Xml.Schema.Validate()extension method for that purpose. The second argument of the Validate() method is aSystem.Xml.ValidationEventHandlerwhich is called on every invalid XML element. It passes aSystem.Xml.ValidationEventArgs. TheValidationEventArgs.Exceptioncan be casted toSystem.Xml.Schema.XmlSchemaValidationException. Now theXmlSchemaValidationExceptionhas a propertySourceObjectwhich I expected to hold a reference to the invalid XML node. Unfortunately it is always null.The following snippet illustrates my usage:
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 } });The validation itself works correctly, but I cannot get a reference on the invalid node. Strangely, the same approach works well for
System.Xml.XmlDocument, but unfortunately I must work withXDocumentin this context.Does anyone have a suggestion how the invalid node can be found in
XDocument?- Moved by Mike FengMicrosoft Contingent Staff, Moderator Friday, January 25, 2013 2:20 AM
All Replies
-
Thursday, January 24, 2013 11:09 AM
OK, I have the answer. The invalid node is the event handler's "sender" itself. It can be cast to XContainer, XElement, ...- Marked As Answer by Alexander SunModerator Friday, January 25, 2013 2:23 AM

