If I read a text file from disk into a stream how can I tell if it might
already be valid XML? I'm writing an app to compare two XML files one of
which may need conversion to XML first. My app will do the conversion when
necessary. I plan to call XMLdiffView, from
http://msdn2.microsoft.com/en-us/library/aa302295.aspx, to generate the
differences report.
See members "ValidationEven tHandler", "ValidationType " and "ValidationFlag s" in class "XmlReaderSetti ngs". Here's a cut-and-paste example:
public void LoadFromFile(st ring fileName)
{
// ...
XmlReaderSettin gs settings = new XmlReaderSettin gs();
settings.Schema s.Add(null, GetSchemaFullFi leName()); // ".xsd" file
settings.Valida tionType = ValidationType. Schema;
settings.Valida tionFlags |= XmlSchemaValida tionFlags.Repor tValidationWarn ings;
///////////////////////////////////////////////////////////////
// Assign an anonymous delegate to trap any schema violations
// when "ReadXml()" is called further below. That is, the
// delegate will be invoked if "fileName" doesn't conform to
// the schema found in the ".xsd" file plugged in above. Note
// that the delegate simply throws an exception on the first
// problem encountered.
///////////////////////////////////////////////////////////////
settings.Valida tionEventHandle r +=
delegate(object sender, ValidationEvent Args args)
{
throw new InvalidFileExce ption(fileName, args.Exception) ;
};
// Create a reader for "fileName" using the above settings
using (XmlReader reader = XmlReader.Creat e(fileName, settings))
{
try
{
////////////////////////////////////////////////////////////
// Read the file into the calling object (us). Note that
// the delegate above will be called if the file doesn't
// conform to the schema file we plugged in earlier. Other
// errors are also possible however but these will normally
// be of type "XmlExcepti on" so we specifically catch that
// below and re-throw it as our own custom exception. Note
// that such errors are usually XML syntax errors however
// so they won't normally be encountered unless someone
// has mucked with the file or otherwise passed some other
// invalid XML file.
////////////////////////////////////////////////////////////
ReadXml(reader) ;
}
catch (XmlException exception)
{
throw new InvalidFileExce ption(fileName, exception);
}
finally
{
reader.Close();
}
}
// ...
}