.Net, ASP.Net, C#, VB.net, SQL Server, Xml, CSS, Design Patterns related tips, tricks, code snippets, articles, links, thoughts, etc. from Binu & Subi Thayamkery.

Binu Thayamkery is a seasoned software architect with more than 13 years of experience in developing enterprise grade connected systems using Microsoft Technologies. In his current position as a lead consultant-solution architect with Prudential Financial, he is working on architecture of next generation investment reporting framework using .net 3.5/WCF/AJAX, etc. He holds a Masters Degree in Computer Science from Colorado State University. Subi Thayamkery is an experienced software developer with more than 8 years of developing various application software systems ranging from workflow automation systems to compliance management tools. She currently works as a technology consultant for Prudential Financial where she helps develop a new system for corportate governance department. She holds an Electrical Engineering degree from New Jersey Institute of Technology.

Monday, December 19, 2005

Validating XML using XMLValidatingReader

Level: Beginner

You can use XmlValidatingReader class to validate an cml file against an XSD schema, Here is the code snippet to do it,



XmlSchemaCollection schemaCol = new XmlSchemaCollection();
schemaCol.Add("",schemaFile);
XmlTextReader textReader = null;
XmlValidatingReader vReader = null;
try
{
textReader = new XmlTextReader(xmlFile);
// create a validating reader.
vReader = new XmlValidatingReader(textReader);
// validate using the schemas stored in the schema collection.
vReader.Schemas.Add (schemaCol);
// set the validation event handler
vReader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// read and validate the XML data.
while (vReader.Read()){}
}
catch (Exception ex)
{
return (false);
}
finally
{
// close the readers

vReader.Close ();
textReader.Close ();
}


And your Event Handler to handle the validation callbacks,

private void ValidationCallBack (object sender, ValidationEventArgs args)
{
this._xmlFeedValid = false;
}



0 comments: