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

已答覆 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
     
      Has Code

    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?

All Replies

  • Thursday, January 24, 2013 11:09 AM
     
     Answered
    OK, I have the answer. The invalid node is the event handler's "sender" itself. It can be cast to XContainer, XElement, ...