EDN Admin
Well-known member
I have an XDocument that I validate against an XML schema. When theXDocument 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 aSystem.Xml.ValidationEventHandler which is called on every invalid XML element. It passes aSystem.Xml.ValidationEventArgs. The ValidationEventArgs.Exception can be casted toSystem.Xml.Schema.XmlSchemaValidationException. Now the XmlSchemaValidationException has a propertySourceObject 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:tempbooksSchema.xml");
// Create the XmlSchemaSet class.
XmlSchemaSet sc = new XmlSchemaSet();
// Add the schema to the collection.
sc.Add("urn:bookstore-schema", @"c:tempbooks.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 forSystem.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?
View the full article
I use the System.Xml.Schema.Validate() extension method for that purpose. The second argument of the Validate() method is aSystem.Xml.ValidationEventHandler which is called on every invalid XML element. It passes aSystem.Xml.ValidationEventArgs. The ValidationEventArgs.Exception can be casted toSystem.Xml.Schema.XmlSchemaValidationException. Now the XmlSchemaValidationException has a propertySourceObject 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:tempbooksSchema.xml");
// Create the XmlSchemaSet class.
XmlSchemaSet sc = new XmlSchemaSet();
// Add the schema to the collection.
sc.Add("urn:bookstore-schema", @"c:tempbooks.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 forSystem.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?
View the full article