How to log all the errors on exception in C# and then show?
private void validateButton_Click(object sender, System.EventArgs e)
{
resultTextBox.Text = String.Empty;
if (ValidateForm())
{
try
{
Cursor.Current = Cursors.WaitCursor;
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(String.Empty, XmlReader.Create(new StreamReader(xmlSchemaFileTextBox.Text)));
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas = schemaSet;
settings.ValidationType = ValidationType.Schema;
XmlRe开发者_StackOverflowader reader = XmlReader.Create(new StringReader(inputXmlTextBox.Text), settings);
while (reader.Read()) { }
resultTextBox.Text = "The XML file is OK :)" +
Environment.NewLine +
DateTime.Now.ToLongDateString();
}
catch (XmlSchemaException schemaEx)
{
resultTextBox.Text = "The XML file is invalid:" +
Environment.NewLine +
schemaEx.LineNumber +
": " +
schemaEx.Message;
}
catch (Exception ex)
{
resultTextBox.Text = ex.ToString();
}
finally
{
Cursor.Current = Cursors.Default;
}
}
else
{
MessageBox.Show(null, "You have to load XML and XSD files to validate.", "There's XML file reading error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
If you want to show the exception to your application's user, you can use ExceptionMessageBox
.
try {
throw new ApplicationException("test");
}
catch (ApplicationException ex)
{
ExceptionMessageBox box = new ExceptionMessageBox(ex);
box.Show(this);
}
you should open the XmlReader
with the XmlReaderSettings
object and use the ValidationEventHandler
to catch errors and report them to the user.
see full documentation and working example at: XmlReaderSettings.ValidationEventHandler Event
basically write something like this:
using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
public class ValidXSD {
public static void Main() {
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);
// Parse the file.
while (reader.Read());
}
// Display any warnings or errors.
private static void ValidationCallBack (object sender, ValidationEventArgs args) {
if (args.Severity==XmlSeverityType.Warning)
Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message);
else
Console.WriteLine("\tValidation error: " + args.Message);
}
}
精彩评论