Wednesday, August 6, 2008

c# .Net XML validate xml file using xsd schema

I talked about using XML file in the last few posts, and especially pointed out the advantage of using xml as interface.
For example: Your mate send you a xml file which contains the information in a format that you defined. You can easily
read and write code without actually getting the xml file because you design the schema.
Now that I successfully create such file, I was wondering the ability to handle errors. I am more aware that what I am gonna
process (xml file) is actually violate the designed format. So I did some research, and did the following things:
  • Generate the schema xsd file for my designed xml file
  • Before processing, using schema xsd file to validate against xml file
  • Report error
Here are some code examples:




if (Validate(strFile, Properties.Settings.Default.schema) != true)
{
MessageBox.Show("XML file doesn't matches the schema! Please verify the input format!");
return;
}

static int numErrors = 0;
static string msgError = "";

private static void ErrorHandler(object sender, ValidationEventArgs args)
{
msgError = msgError + "\r\n" + args.Message;
numErrors++;
}

private static bool Validate(string xmlFilename, string xsdFilename)
{
return Validate(GetFileStream(xmlFilename), GetFileStream(xsdFilename));
}

private static void ClearErrorMessage()
{
msgError = "";
numErrors = 0;
}

// returns a stream of the contents of the given filename
private static Stream GetFileStream(string filename)
{
try
{
return new FileStream(filename, FileMode.Open, FileAccess.Read);
}
catch
{
return null;
}
}

private static bool Validate(Stream xml, Stream xsd)
{
ClearErrorMessage();
try
{
XmlTextReader tr = new XmlTextReader(xsd);
XmlSchemaSet schema = new XmlSchemaSet();
schema.Add(null, tr);

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(schema);
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ErrorHandler);
XmlReader reader = XmlReader.Create(xml, settings);

// Validate XML data
while (reader.Read())
;
reader.Close();

// exception if validation failed
if (numErrors > 0)
throw new Exception(msgError);

tr.Close();
return true;
}
catch
{
msgError = "Validation failed\r\n" + msgError;
return false;
}
}



505 comments:

«Oldest   ‹Older   1001 – 505 of 505
«Oldest ‹Older   1001 – 505 of 505   Newer› Newest»