I have XDocumentone that I am checking against an XML schema. If the value is XDocumentinvalid, I need to find invalid XML nodes so that the user can easily navigate to the appropriate place in my application (for example, by double-clicking a message in the message grid).
I use the extension method System.Xml.Schema.Validate()for this purpose. The second argument to the Validate () method is one System.Xml.ValidationEventHandlerthat is called for each invalid XML element. He passes a System.Xml.ValidationEventArgs. ValidationEventArgs.Exceptionmay be dropped before System.Xml.Schema.XmlSchemaValidationException. Now it
XmlSchemaValidationExceptionhas a property SourceObjectthat, as I expected, will contain a link to an invalid XML node. Unfortunately, it is always zero.
The following snippet illustrates my use:
XDocument doc = XDocument.Load(@"c:\temp\booksSchema.xml");
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add("urn:bookstore-schema", @"c:\temp\books.xsd");
doc.Validate(sc, delegate(object sender, ValidationEventArgs e)
{
XmlSchemaValidationException ve = e.Exception as XmlSchemaValidationException;
if (ve != null)
{
object errorNode = ve.SourceObject;
}
});
The check itself is performed correctly, but I cannot get a link to an invalid node. Oddly enough, the same approach is well suited for System.Xml.XmlDocument, but unfortunately I have to work with XDocumentin that context.
Does anyone have a suggestion on how an invalid node can be found in XDocument?
source