How to find an invalid XML node in an XDocument that is checked against a schema (XmlSchemaValidationException.SourceObject is null)

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");

// 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 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?

+5
source
1

, . node "". XContainer, XElement,...

+6

All Articles