Paul wrote:
string sValue = propertyInfo.GetValue(souceObject, null)
as string;
// Now we need to determine if it is in a format for
loading.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Auto;
settings.ValidationFlags |=
System.Xml.Schema.XmlSchemaValidationFlags.None;
settings.ValidationEventHandler += new
System.Xml.Schema.ValidationEventHandler(settings_ ValidationEventHandler);
XmlReader reader = XmlReader.Create( new
MemoryStream( Encoding.Default.GetBytes( sValue ) ), settings);
while (reader.Read()) ;
if (isValidXml == false)
{
failureMessage = string.Format("Invalid Xml provided
in {0}", propertyInfo.Name);
}
return isValidXml;
But this still raises an exception.
The string it is attempting to validate is "rubbish".
This does not cause the reader to hit the validation handler.
But instead throws an unhandled exception.
Your attempt is not clear to me.
If you want to check for well-formedness only then you do not need any
validation event handler, you simply need to set up the reader and have
that while loop reading through. It will throw an exception however if
the markup is not well-formed so avoiding an exception is not possible
as far as I see it, what you can avoid is using XmlDocument, you only
need an XmlReader.
If you want to perform a validation then that only makes sense if you
provide a schema or several schemas as validation is done against a
schema or schema set. In that case you need to a validation event
handler which will then be called for every validation error but not for
well-formedness errors.
And there is no need to use memory streams and encodings, the XmlReader
can deal with all of that much better than your above code, you can
simply do e.g.
using (XmlReader xmlReader = XmlReader.Create(new StringReader(sValue)))
try {
while (xmlReader.Read()) {}
}
catch (XmlException e) {
// deal with error here
}
}
I hope that is clearer now, you need to distinguish between
well-formedness checks and validation.
--
Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/