Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an XDocument that I validate against an XML schema. When the XDocument 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).

I use the System.Xml.Schema.Validate() extension method for that purpose. The second argument of the Validate() method is a System.Xml.ValidationEventHandler which is called on every invalid XML element. It passes a System.Xml.ValidationEventArgs. The ValidationEventArgs.Exception can be casted to System.Xml.Schema.XmlSchemaValidationException. Now the XmlSchemaValidationException has a property SourceObject which 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 with XDocument in this context.

Does anyone have a suggestion how the invalid node can be found in XDocument?

like image 386
loki Avatar asked Jan 21 '13 20:01

loki


1 Answers

OK, I have the answer. The invalid node is the event handler's "sender" itself. It can be cast to XContainer, XElement, ...

like image 159
loki Avatar answered Sep 29 '22 16:09

loki